开发者

Ruby: what is an easy way to check of all values in a 2D array are the same in a particular column or row?

开发者 https://www.devze.com 2023-02-07 21:39 出处:网络
[[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, 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.

0

精彩评论

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