tags:

views:

96

answers:

4

Given an n x m array of boolean:

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

what is the shortest code that can return "how many true are there in that column?"

the result should be

[1, 3, 2] 
+6  A: 

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} }
sepp2k
wow works in Ruby 1.9.1. Is there a solution for 1.8.6?
動靜能量
It works in 1.8.7, too. For 1.8.6 you can probably get the count method from backports or active_support. If that's not an option, you can write it using inject.
sepp2k
Elegant, but not very verbose. +1 anyway.
You
seems like you can also use: count(true)instead of: count{|x| x}
Ragmaanir
@Ragmaanir: Nice. Good suggestion.
sepp2k
A: 
array = [[true, true, false],
         [false, true, true],
         [false, true, true]]
array.transpose.map {|x| x.count {|y| y}}
igorgue
A: 

Here's another solution:

b.transpose.collect{|x| x.reject{|y| y != true}.length}
You
A: 
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}
gnibbler
You can save two more with `a.transpose.map{|c|c.count !!0}`
Jonas Elfström