Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Finding duplicates within an array

Status
Not open for further replies.

HughbertD

Technical User
Apr 30, 2007
42
GB
Hi all,

I am writing a program, so far I have written the contents of the file (in this case filenames) into an array - now I want to find any duplicate filenames within the array and print them to another file - I am having a hard time getting my head around the logic to do this?

Can anyone help?
 
Hi

Brute force :
Code:
for ($i=0;$i<(scalar @a)-1;$i++) {
  for ($j=$i+1;$j<scalar@a;$j++) {
    print "$a[$i] duplicated at position $i and $j\n" if $a[$i] eq $a[$j];
  }
}
The same but deals nicer with multiple positions :
Code:
for ($i=0;$i<(scalar @a)-1;$i++) {
  $s="";
  for ($j=$i+1;$j<scalar@a;$j++) {
    $s.=($s?"":$i).", $j" if $a[$i] eq $a[$j];
  }
  print "$a[$i] at positions $s\n" if $s;
}

Feherke.
 
Thank you for the reply -

@a is my array with filenames in?

 
Use a hash:

Code:
my %counter;
$counter{$_}++ for @filenames;

print "Duplicates\n";
for (keys $counter) {
   print "$_\n" if ( $counter{$_} > 1 );
}
 
Hi Ishnid -

I get this error - I know so little about hashes I'm not sure what it means

Type of arg 1 to keys must be hash (not scalar dereference) at add_file_map.pl line 35, near "$counter) "
Execution of add_file_map.pl aborted due to compilation errors.
 
it's a typo:
the for() loop should read:
Code:
for (keys %counter) {
 
There must be a problem with the logic of the hash as it prints out each element of the array without duplication : where as I was hoping for every element of the array that had a duplicate
 
Ignore that post above - me being stupid - theres a problem in a loop earlier where I put the information into the array causing the array to have lots of duplicates for every entry -

Thanks for everyones help on this
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top