in reply to How do I remove the duplicates from the array?
Your specification is very unlclear. That is what I made of it: you want to keep a tuple in both arrays if the number in the top array (key) appears only once or the corresponding value from array 2 is greater than all corresponding values to the same key.
#!/usr/bin/perl use warnings; use strict; my @array = qw(-20 20 1 1 2 2 2 9 3 -4 -4 5 -20 20 7 7 7); my @array1 = qw( 10 11 7 9 3 3 3 1 3 4 5 5 1 30 8 7 8); my %hash; for my $i (0 .. $#array) { my $first = $array[$i]; my $second = $array1[$i]; if (not exists $hash{$first}{highest}) { # The key seen for the first time. $hash{$first}{highest} = $second; } else { # The highest value seen again. $hash{$first}{delete} = 1 if $second == $hash{$first}{highest} +; # A new highest value. if ($second > $hash{$first}{highest}) { $hash{$first}{highest} = $second; $hash{$first}{delete} = 0; } } } # Delete repeated max values. for my $key (keys %hash) { delete $hash{$key} if $hash{$key}{delete}; } my (@output, @output1); for my $i (0 .. $#array) { if (exists $hash{ $array[$i] } and $array1[$i] == $hash{ $array[$i] }{highest}) { push @output, $array[$i]; push @output1, $array1[$i]; } } print "@output\n@output1\n";
Updated : Fixed a bug, added 7 to show the problem (the previous version did not delete 7 because there was a lesser value).
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: How do I remove the duplicates from the array?
by AnomalousMonk (Archbishop) on Sep 25, 2013 at 22:59 UTC | |
Re^2: How do I remove the duplicates from the array?
by PetreAdi (Acolyte) on Sep 26, 2013 at 06:23 UTC | |
by choroba (Cardinal) on Sep 26, 2013 at 07:30 UTC | |
by parv (Parson) on Sep 26, 2013 at 07:49 UTC | |
by farang (Chaplain) on Sep 26, 2013 at 07:09 UTC |
In Section
Seekers of Perl Wisdom