开发者

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

开发者 https://www.devze.com 2023-01-09 23:21 出处:网络
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 tru开发者_StackOverflow中文版e are there in that c

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 tru开发者_StackOverflow中文版e are there in that column?"

the result should be

[1, 3, 2] 


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} }


array = [[true, true, false],
         [false, true, true],
         [false, true, true]]
array.transpose.map {|x| x.count {|y| y}}


Here's another solution:

b.transpose.collect{|x| x.reject{|y| y != true}.length}


a=[[true, true, false],
   [false, true, true],
   [false, true, true]]

a.transpose.map{|c|c.count(true)}

sneaky way of saving one more character

a.transpose.map{|c|c.count(!!0)}

As Jonas points out it is possible to golf this some more

a.transpose.map{|c|c.count !!0}
0

精彩评论

暂无评论...
验证码 换一张
取 消