CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Common Value for three arrays

 



terrylau
New User

Apr 13, 2010, 8:52 PM

Post #1 of 3 (1693 views)
Common Value for three arrays Can't Post

Perl newbie hereÖ need some help and suggestions. Iíve searched for many examples but so far itís all for array operation for two arrays. I have three arrays and want to find the common value in the three array and list them out :

Array 1 = {0, 1,2,3,4,5,6,7,8,9}
Array 2 = {1,2,3,4,6,8, 10, 12,14}
Array 3 = {1,2,3,5,7,9, 11,13,15}

I want the output to be something like below:


Code
       Array 1 	Array 2	     Array 3 
0 yes
1 yes yes yes
2 yes yes yes
3 yes yes yes
4 yes yes
5 yes yes
6 yes yes
7 yes yes
8 yes yes
9 yes yes
10 yes
11 yes
12 yes
13 yes
14 yes
15 yes


The idea is to list out the output as above. Iíve started with something below which I got from another website but got stuck :


Code
#!/usr/bin/perl 
use strict;
use warnings;
my @array1;
my @array2;
my @diff;
my @isect;
my $item;
my %count;
@array 1 = (0, 1,2,3,4,5,6,7,8,9);
@array 2 = (1,2,3,4,6,8, 10, 12,14);
@isect = ( );
@diff = ( );
%count = ( );
foreach $item (@array1, @array2) { $count{$item}++;}
foreach $item (keys %count) {
if ($count{$item} == 2) {
push @isect, $item;
} else {
push @diff, $item;
}
}
print "\nA Array = @array1\n";
print "\nB Array = @array2\n";
print "\nIntersect Array = @isect\n";
print "\nDiff Array = @diff\n\n";

Appreciate the help



roolic
User

Apr 13, 2010, 9:26 PM

Post #2 of 3 (1691 views)
Re: [terrylau] Common Value for three arrays [In reply to] Can't Post

the best way to check the required value is using the hash:

Code
my %hash = map {$_ => 1} @array; 
print "$val exists" if $hash{$val};


so your code should be look like:

Code
my @array1 = ( .. ); 
my @array2 = ( .. );
my @array3 = ( .. );

my @all_unique_sorted = sort{ $a <=> $b }
keys %{ map { $_=> 1 } (@array1, @array2, @array3) };

foreach my $value ( @all_unique_sorted ){
print $value;
foreach my $arr_ref( \@array1, \@array2, \@array2 ){
print "\t". exists( $arr_ref, $value );
}
print "\n";
}

sub exists{
my($array, $value) = @_;
my %all_vals = map { $_=>1 } @{$array};
return $all_vals{$value} ? 'yes' : '';
}



rovf
Veteran

Apr 14, 2010, 12:36 AM

Post #3 of 3 (1684 views)
Re: [terrylau] Common Value for three arrays [In reply to] Can't Post

This is crossposted here: [URL}http://perlmonks.org/index.pl?node_id=834597

Please do not crosspost; or if you do, at least mention this in your post.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives