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: Beginner:
unique patterns in a multidimensional array

 



PerlBeginner31
Novice

Apr 4, 2014, 11:05 AM

Post #1 of 5 (1483 views)
unique patterns in a multidimensional array Can't Post

How to fine the unique patterns in an array of arrays?

@arr[0] = [1,0,1,1,0];
@arr[1] = [1,0,1,1,1];
@arr[2] = [1,0,1,1,0];
@arr[3] = [1,0,1,1,0];

The output should be [1,0,1,1,0], [1,0,1,1,1].

Please help.


BillKSmith
Veteran

Apr 4, 2014, 12:43 PM

Post #2 of 5 (1478 views)
Re: [PerlBeginner31] unique patterns in a multidimensional array [In reply to] Can't Post

Use a hash.

Code
use strict; 
use warnings;
my @array = (
[1,0,1,1,0],
[1,0,1,1,1],
[1,0,1,1,0],
[1,0,1,1,0],
);

my %hash = map {join('|', @$_), $_} @array;
local $" = ',';
print "[@$_], " foreach values %hash;

Good Luck,
Bill


PerlBeginner31
Novice

Apr 5, 2014, 12:22 AM

Post #3 of 5 (1471 views)
Re: [BillKSmith] unique patterns in a multidimensional array [In reply to] Can't Post

Thanks a lot for the solution..


PerlBeginner31
Novice

Apr 5, 2014, 12:52 AM

Post #4 of 5 (1470 views)
Re: [PerlBeginner31] unique patterns in a multidimensional array [In reply to] Can't Post

Now how to find how many times each of these pattern occurs in that array?


Laurent_R
Veteran / Moderator

Apr 5, 2014, 2:33 AM

Post #5 of 5 (1466 views)
Re: [PerlBeginner31] unique patterns in a multidimensional array [In reply to] Can't Post

Hi,
just putting again here the explanations that I put in your duplicate post:

One possibility is to stringify the rows and use the resulting strings to populate a hash with the number of occurrences. For example, you could try this:

Code
use strict; 
use warnings;
my @arr = (
[1,0,1,1,0],
[1,0,1,1,1],
[1,0,1,1,0],
[1,1,1,1,1],
[1,0,0,0,0],
[1,0,1,1,0],
);

my %hash;
for my $row (@arr) {
my $string = join ",", @$row;
$hash{$string} ++;
}
print "$_ : $hash{$_}\n" for keys %hash;


which will print:

Code
1,0,1,1,0 : 3 
1,1,1,1,1 : 1
1,0,0,0,0 : 1
1,0,1,1,1 : 1

Please note that the way you are populatinq the array of arrays is wrong (or, to say the very least, deprecated). Since [1,0,1,1,0] is an array reference, it is in fact a scalar. The right syntax would therefore be:


Code
my @arr; 
$arr[0] = [1,0,1,1,0];
$arr[1] = [1,0,1,1,1];
...

Or what I have shown in the code snippet above. Perl would have told you if you had used the:

Code
use strict; 
use warnings;

pragmas, which you should consider as mandatory for any program having more than two lines of code.

 
 


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

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