Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Comparing two arrays

by sk (Curate)
on Feb 25, 2006 at 17:50 UTC ( #532787=note: print w/ replies, xml ) Need Help??


in reply to Comparing two arrays

Something like this? -

#!/usr/bin/perl use strict; use warnings; my @x = qw (hi there hello there hello world); my @y = qw (hi there hello new element there there); my (%xh,%yh) = (); # count the number of repeats in each array $xh{$_}++ for (@x); $yh{$_}++ for (@y); my $common = 0; # for all keys in the hash check if it exists in the other hash. if it + does then choose the min of the two for number of repeats. for (keys %xh) { $common += min($xh{$_}, $yh{$_}) if (exists($yh{$_})); } print "Number common = $common\n"; sub min { return (($_[0] <= $_[1]) ? $_[0] : $_[1]); }

Output

Number common = 4

In the above list we have hi (1), there (2), hello(1). Note: I have not tested it extensively.

cheers

SK


Comment on Re: Comparing two arrays
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://532787]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (7)
As of 2014-12-22 06:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (110 votes), past polls