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 true
s 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}
精彩评论