Advertisement
Guest User

ovid-puzzle

a guest
Dec 9th, 2014
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.94 KB | None | 0 0
  1. #!perl
  2.  
  3. =head http://blogs.perl.org/users/ovid/2014/12/a-small-puzzle-for-you.html
  4.  
  5. Given several arrays, each of which has elements which are a subset of allowed elements,
  6. and given that every allowed element appears at least once in each array,
  7. how do I rewrite all arrays such that each element of each array which has an identical value to an element
  8. in another array has the same index number in each array, with missing elements being undef?
  9.  
  10. =cut
  11.  
  12. @a = ( 'b', 'c', 'f' );
  13. @b = ( 'a', 'd' );
  14. @c = ( 'c', 'd', 'e' );
  15.  
  16. my @arrs = (\@a, \@b, \@c);
  17. my %h;
  18. $h{$_}++ for map{ +(@$_) } @arrs;
  19. my @list = sort keys %h;
  20.  
  21. my @new_arrs;
  22. for( my $i = 0; $i < @list; $i++ ){
  23.     for(my $a = 0; $a < @arrs; $a++){
  24.         my $val = $list[$i];
  25.         $val = undef unless( grep {$list[$i] eq $_ } @{$arrs[$a]} );
  26.         push @{$new_arrs[$a]}, $val;
  27.     }
  28. }
  29.  
  30. use Data::Dumper;
  31. $Data::Dumper::Indent = 1;
  32. print Dumper \@new_arrs;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement