The code below gives the correct results, although I'm mystified by the specs. If I understand them correctly, the sort order of the keys determines which array is to be consider the reference array, as well as the flow of the rest of the algorithm, which sounds strange to me. I suspect that align_arrays should really operate on AoAs, not HoAs.

use strict; use warnings; 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"], ); print_aoa( 'AoA1', align_array( %hoa1 ) ); print_aoa( 'AoA2', align_array( %hoa2 ) ); sub align_array { my %h = @_; my @keys = sort keys %h; # huh? why should sort order # dictate the reference array? my $ref = $h{ $keys[ 0 ] }; my @ret = map [ $_ ], @$ref; for my $i ( 0 .. $#{ $ref } ) { # $i determines the row in @ret my $elem = $ref->[ $i ]; for my $j ( 1 .. $#keys ) { # $j determines the col in @ret my $arr = $h{ $keys[ $j ] }; $ret[ $i ][ $j ] = '-'; for my $k ( 0 .. $#{ $arr } ) { if ( $elem eq $arr->[ $k ] ) { $ret[ $i ][ $j ] = $elem; splice @$arr, 0, $k + 1; last; } } } } return \@ret; } sub print_aoa { my ( $name, $aoa ) = @_; print '@', $name, ' = (', $/; for my $arr ( @$aoa ) { print ' [', join( ',', @$arr ), ']', $/; } print ')', $/; } __END__ @AoA1 = ( [A,A,A,A] [B,B,-,B] [C,-,-,C] [D,-,D,-] ) @AoA2 = ( [A,A,-] [D,-,-] )

the lowliest monk


In reply to Re: Aligning Arrays Problem by tlm
in thread Aligning Arrays Problem by monkfan

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.