Ruby: what is an easy way to check of all values in a 2D array are the same in a particular column or row?
[[0, 1, 2],
[2, 1, 0],
[0, 1, 2]]
What is an easy way to check of this matrix has all valu开发者_Go百科es down a column the same?
[[0, 1, 0],
[2, 2, 2],
[0, 1, 2]]
And then horizontally?
1.
a.map{|row|row[x]}.uniq.size == 1
or
a.transpose[x].uniq.size == 1
2.
a[x].uniq.size == 1
To check whether there's a row in which all items are the same, you can do:
array.any? do |row|
row.all? {|item| row[0] == item }
end
To check whether there's a column, you can first transpose the array and then do the same.
精彩评论