Retrieving the corresponding values ​​from a list based on the unique value index in another list - Perl

advertisements

I want to get the corresponding values from the second list based on the index value of the unique values in my first list using perl.

For ex:

@list1=('a','b','c','a','d');
@list2=('e','f','g','a','i');

i want to create two new list without the duplicate values

@new_list1=('a','b','c','d');
@new_list2=('e','f','g','i');

How can i do this?

to get unique values from one list i can use:

my %temp_hash = map { $_, 0 } @list1;
my @uniq_array = keys %temp_hash;
print "@uniq_array\n";

But how to get the values at the corresponding index from the other list.

Thanks in advance.

EDIT: It should find unique values based on some condition and not the first occurrence. for ex:

@list1=('a','b','c','a','d');
@list2=('e','f','g','a','i');

and

@list1=('a','b','c','a','d');
@list2=('a','f','g','e','i');

should give the same value:

@new_list1=('a','b','c','d');
@new_list2=('e','f','g','i');

In the given example the condition may be not to include the common element where the value for both the list are same. ie there are two occurrence of 'a' 1st 'a' corresponds to 'e' and 2nd 'a' corresponds to 'a'. so the second one is to be removed not the first one.


When dealing with parallel arrays, one deals with indexes. To find the list of indexes, one can start with the following common method of finding unique values:

my %seen;
my @uniq = grep !$seen{$_}++, @dups;

and expand it to take a list of indexes as input:

my %seen;
my @indexes = grep !$seen{ $list1[$_] }++, 0..$#list1;

In your updated question, you need something more complex:

my %options;
for (0..$#list1) {
   push @{ $options{ $list1[$_] } }, $_;
}

my %seen;
my @indexes;
for (0..$#list1) {
   next if $seen{$_}++;
   my @options = @{ $options{ $list1[$_] } };
   my $option = pick(\@list1, \@list2, \@options) // $options[0];
   push @indexes, $option;
}

Then all you have to do is extract the desired elements:

my @new_list1 = @list1[ @indexes ];
my @new_list2 = @list2[ @indexes ];

The pick function for the possible selection algorithm you describe is:

sub pick {
   my ($list1, $list2, $options) = @_;
   return ( grep $list1->[$_] ne $list2->[$_], @options )[0];
}