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:
Find the number of occurrences of the rows in a multidimensional array

 



PerlBeginner31
Novice

Apr 4, 2014, 10:35 AM

Post #1 of 4 (1553 views)
     Find the number of occurrences of the rows in a multidimensional array  

I want a solution to find how many times each row pattern is present in the array.

For example, in the following multidimensional array,

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

[1,0,1,1,0] occurs thrice. Similarly, how many times each pattern occurs.

Please help.


Laurent_R
Veteran / Moderator

Apr 5, 2014, 2:17 AM

Post #2 of 4 (1540 views)
     Re: [PerlBeginner31] Find the number of occurrences of the rows in a multidimensional array [In reply to]  

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.


PerlBeginner31
Novice

Apr 5, 2014, 2:25 AM

Post #3 of 4 (1538 views)
     Re: [Laurent_R] Find the number of occurrences of the rows in a multidimensional array [In reply to]  

Thanks a lot for the detailed explanation.


Laurent_R
Veteran / Moderator

Apr 5, 2014, 2:35 AM

Post #4 of 4 (1533 views)
     Re: [PerlBeginner31] Find the number of occurrences of the rows in a multidimensional array [In reply to]  

This is a duplicate post of:

http://perlguru.com/gforum.cgi?post=78306;sb=post_latest_reply;so=ASC;forum_view=forum_view_collapsed;;page=unread#unread

Locking this thread so that answers will be limited to the other post.


(This post was edited by Laurent_R on Apr 5, 2014, 2:36 AM)

 
 


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

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