Question

In Ruby I would have this array of arrays:

[[1,1,1,0,0],[1,1,1,0,0],[0,0,0,1,1]]

which translates into this matrix or table (no headers):

11100
11100
00011

What I want to do is to take every element of each array in the array to transpose the array, for instance, in the above table/array I would have this output as an array of arrays:

[[1,1,0],[1,1,0],[1,1,0],[0,0,1],[0,0,1]]

or this table

110
110
110
001
001

Finally, once the above is accomplished, I would like to convert every array in the array to a string which would exclude any values that are not consecutive 1s, for instance, if I convert the array [1,0,1,1,1,0,1] to a string where the non consecutive 1s are excluded I should get something like this: 111. Note that the first, second, sixth and seventh element are excluded because they are not consecutive 1s.

Was it helpful?

Solution

For the first part, all you need is Array#transpose.

array.transpose
#=>  [[1,1,0],[1,1,0],[1,1,0],[0,0,1],[0,0,1]]

then you can do the following

.map {|arr| arr.join.scan(/11+/)}

to count the consecutive ones. The join converts each subarray to a string, then scan checks for two or more consecutive 1s.

Altogether:

array.transpose.map {|arr| arr.join.scan(/11+/)}
#=> [["11"], ["11"], ["11"], [], []]

If you want to remove the empty arrays, @Doorknob notes that you can append a reject:

array.transpose.map {|arr| arr.join.scan(/11+/)}.reject(&:empty?)
#=> [["11"], ["11"], ["11"]]

OTHER TIPS

You could also use Enumerable#chunk:

Code

array.transpose
     .map { |a|
       a.chunk { |e| e }
        .select { |f,a| f == 1 && a.size > 1 }
        .map { |_,a| a.join } }

Example

array = [[1,1,1,0,0],[1,1,0,1,0],[0,0,1,1,1],[1,1,0,1,1],[1,0,1,1,1]]
  #=> [["11", "11"], ["11"], [], ["1111"], ["111"]]

One could eliminate the empty set, if desired.

Explanation

For array above,

a = array.transpose
  #=> [[1, 1, 0, 1, 1],
  #    [1, 1, 0, 1, 0],
  #    [1, 0, 1, 0, 1],
  #    [0, 1, 1, 1, 1],
  #    [0, 0, 1, 1, 1]]

a.map iterates over the elements (rows) of a. Consider the first element:

b = a.first
  #=> [1, 1, 0, 1, 1]
c = b.chunk { |e| e }
  #=> #<Enumerator: #<Enumerator::Generator:0x000001020495e0>:each>

To view the contents of this enumerator, add .to_a

  b.chunk { |e| e }.to_a
    #=> [[1, [1, 1]], [0, [0]], [1, [1, 1]]]
d = c.select { |f,a| f == 1 && a.size > 1 }
  #=> [[1, [1, 1]], [1, [1, 1]]]
d.map { |_,a| a.join }
  #=> ["11", "11"]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top