Ruby: what is an easy way to check 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 this matrix, all values ​​in the column are the same?

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

And then horizontally?

+3
source share
2 answers

1.

a.map{|row|row[x]}.uniq.size == 1

or

a.transpose[x].uniq.size == 1

2.

a[x].uniq.size == 1
+4
source

To check if there is a line in which all elements are the same, you can do:

array.any? do |row|
  row.all? {|item| row[0] == item }
end

To check if there is a column, you can first move the array and then do the same.

+1
source

Source: https://habr.com/ru/post/1788613/


All Articles