Subj : Re: any function to handle this kind of counting? To : comp.programming From : John W. Krahn Date : Wed Aug 03 2005 02:00 pm Rob Thorpe wrote: > Peter Ammon wrote: >>Just wait 'til the Perl guy gets here, though! > > I can take on that mantle: > > for(0..($#a<$#b?$#a:$#b)){++$ans{$b[$_]}{$a[$_]};} Way too much punctuation and not enough whitespace. :-) ++$ans{ $b[ $_ ], $a[ $_ ] } for 0 .. ( @a < @b ? $#a : $#b ); > This is probably close to the shortest solution that can be done in any > language - but it's horrible. Like all the other "terse" solutions it > misses the point. In a real program you'll have to document exactly > why you're doing this operation and how. Doing so will take a > significant number of lines. > > For example documenting the perl: > > # Now we have two arrays @a and @b we need to count each > # char-interger pair across these two arrays. For example in: > # @a = ('a', 'b', 'a', 'e', 'a'); > # @b = ( 1, 2, 1, 4, 5); there are the pairs > # (1 ('a' 2)) (2 ('b' 1)) (4 ('e' 1)) (5 ('a' 1)) > for ($i) (0..(($#a < $#b) ? $#a : $#b)) { # Find smallest array ^^^^ Syntax error > # Make %ans a hash-of-hashes containing the answer > ++$ans{$b[$i]}{$a[$i]}; > } You don't really need a hash of hashes as perl will concatenate comma separated values in the hash key. $ perl -e' @a = qw/ a b a e a /; @b = qw/ 1 2 1 4 5 /; $; = ""; # change the subscript separator ++$ans{ $b[ $_ ], $a[ $_ ] } for 0 .. ( @a < @b ? $#a : $#b ); print "$_\t$ans{$_}\n" for sort keys %ans; ' 1a 2 2b 1 4e 1 5a 1 John -- use Perl; program fulfillment .