1. For every elements in array 2. Assign elem[0] of array in key1,key2,key3 etc to an empty array (we call it: $AoA[0]) So it'll be as many as 4 arrays (= size of array in hash) e.g. $AoA[0] ..$AoA[3] filled up with elem[0] of all hashes $AoA[0][0]="A",$AoA[1][0] ="B", $AoA[2][0]="C",$AoA[3][0]="D" Or if you will at this point we have @AoA = ([A],[B],[C],[D]) Every element of arrays in first key *becomes* first element of new array in @AoA 3. Check if the elements of next array are equal e.g Check: elem[0]-key1 = elem[0]-key2 4. If they are equal, store elem[0]-key2 in $AoA[0], then go to next hash (elem[0]-key3)..etc 5. If they are not equal, check if elem[0]-key1 = elem[1]-key2 ..etc until elem[last]-key2 (exhaust all element of array in key2) If they are >1 matches, take only the *first* matching one. If after exhausting it, still cannot find, assign '-' (dash) to $AoA[0] etc. 6. While checking, check elem[0]-key1 ..elem[last]-key1 with elements of next array of key2-key4, verify if elem[0]-key2 has been *used* for previous match, if yes then check elem[0]-key1 = elem[1]-key2, = elem[2]-key2 ... = elem[last]-key2, otherwise match it (assign elem[0]-key1 = elem[0]-key2 ). 7. Finally we have an AoA with $AoA[1] ..$AoA[4] filled up (see answers snippet below)
My questions:#!/usr/bin/perl -w use strict; use Data::Dumper; my %hoa1 = ( 'key1' => ["A","B","C","D"], 'key2' => ["A","C","D","B"], 'key3' => ["C","A","D","H"], 'key4' => ["A","B","I","C"], ); my %hoa2 = ( 'key1' => ["A","D"], 'key2' => ["A","B"], 'key3' => ["C","H"], ); my @answ = align_array(%hoa1); print Dumper \@answ; sub align_array { my %hoa = @_; my @AoA; my @keys = sort keys %hoa; foreach my $id ( -1 .. $#keys-1 ) { for ( 0 .. $#{$hoa{$keys[$id]}} ) { #Here I get point No.2 done $AoA[$_][0] = $hoa{$keys[0]}[$_]; # I'm totally stuck here, in attempt to do point No.3 to 7 # How can I evaluate elements of array of varying size # dynamically? if ( $AoA[$_][0] = $hoa{$keys[$id+1]}[$_] ) { $AoA[$_][$_+2] = $hoa{$keys[$id+1]}[$_]; } elsif ( $AoA[$_][0] = $hoa{$keys[$id+3]}[$_] ) { $AoA[$_][$_+2] = $hoa{$keys[$id+3]}[$_]; } else { $AoA[$_+1][$_+2] = "-"; } } } # ----- end foreach ----- return @AoA ; }
Desperately in need of your enlightenments. Thanks beforehand.# For @answ_hoa1, note that 2nd elem of 4th array is "-" and not "D" # because elem[last] in 2nd array ("B") has been *used* before my @answ_hoa1 = ( ["A","A","A","A"], ["B","B","-","B"], ["C","-","-","C"], ["D","-","D","-"], ); my @answ_hoa2 = ( ["A","A","-"], ["D","-","-"], );
In reply to Aligning Arrays Problem by monkfan
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |