Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Ruby, what is a simple way to count how many true in each column of n x m array?

Tags:

ruby

Given an n x m array of boolean:

[[true, true, false],
 [false, true, true],
 [false, true, true]]

what is a simple way that can return "how many true are there in that column?"

the result should be

[1, 3, 2] 
like image 717
nonopolarity Avatar asked Aug 01 '10 12:08

nonopolarity


1 Answers

Use transpose to get an array where each subarray represents a column and then map each column to the number of trues in it:

arr.transpose.map {|subarr| subarr.count(true) }

Here's a version with inject that should run on 1.8.6 without any dependencies:

arr.transpose.map {|subarr| subarr.inject(0) {|s,x| x ? s+1 : s} }
like image 135
sepp2k Avatar answered Sep 30 '22 13:09

sepp2k