Check array elements of the same size

Is there a better and effective way to check if the elements of an array have the same sizes?

[[1,2], [3,4], [5]] => false [[1,2], [3,4], [5,6]] => true 

What I have:

 def element_of_same_size?(arr) arr.map(&:size).uniq.size == 1 end 

Another solution:

 def element_of_same_size?(arr) arr[1..-1].each do |e| if e.size != arr.first.size return false else next end end return true end 

This one will return false immediately when it finds an item that is not the same size as the first.

Is there a better way to do this? (Sure...)

+4
source share
6 answers

How about using the Enumerable#all? method Enumerable#all? ?

 def element_of_same_size?(arr) arr.all? { |a| a.size == arr.first.size } end element_of_same_size?([[1,2], [3,4], [5]]) # => false element_of_same_size?([[1,2], [3,4], [5, 6]]) # => true 
+13
source

To deliver another single-line image:

Can you use chunk and one?

 [[1,2], [3,4], [7,8], [5,6]].chunk(&:size).one? 
+3
source

I like the toro2k answer. I just wanted to add the ability to add a method to the class of the array itself and warn you that elements that are not arrays but respond to the size method can return true. (edit: false if empty array)

 class Array def same_element_size? return false if self.empty? sz = self.first.size self.all? {|k| k.size==sz} end end ar = [[1,2], [3,4], [5]] ar2 = [[1,2], [3,4], [5,6]] ar3 = [[1,2], 'hi', [4,5]] [[], ar, ar2, ar3].each {|array| puts "%30s --> %s" % [array.inspect, array.same_element_size?] } # [] --> false # [[1, 2], [3, 4], [5]] --> false # [[1, 2], [3, 4], [5, 6]] --> true # [[1, 2], "hi", [4, 5]] --> true 
+2
source

Just for fun, if the Array extension is your choice, can you go for something more flexible, like implementing the same? method same? :

 class Array def same? &block if block_given? f = block.call(first) all? {|a| block.call(a) == f} else all? {|a| a == first } end end end 

This allows:

 [[1,2], [5,6], [8,9]].same?(&:size) 

or

 [[1,2], [7,8], [5,6], [8,9]].same?(&:max) 

or just (by default it will be compared with == )

 [[1,2], [7,8], [5,6], [8,9]].same? 
+2
source

Some guidelines:

  user system total real standalone all 0.234000 0.000000 0.234000 ( 0.246025) class method all 0.234000 0.000000 0.234000 ( 0.235024) class method transpose 0.920000 0.000000 0.920000 ( 0.940094) chunk and one? 1.591000 0.000000 1.591000 ( 1.610161) 

Does my money relate to a class method using Enumerable # all? from toko2k

0
source

If you are dealing with an array of non-nested arrays, you can check that the matrix is ​​square. It throws recursive arrays from the window, but is concise.

 require 'matrix' a1 = [[1,2],[3,4],[5,6]] a2 = [[1,2,3],[4,5,6]] a3 = [[1,2],3,4,[5,6]] Matrix[a1].square? == true Matrix[a2].square? == true Matrix[a3].square? == false 
0
source

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


All Articles