1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Common value in three arrays

Discussion in 'Perl' started by terrylau, Apr 14, 2010.

  1. terrylau

    terrylau New Member

    Joined:
    Jul 2, 2009
    Messages:
    12
    Likes Received:
    0
    Trophy Points:
    0
    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
     

Share This Page