有没有一种最好有效的方法来检查数组的元素是否大小相同?
[[1,2], [3,4], [5]] => false
[[1,2], [3,4], [5,6]] => true
我得到了什么:
def element_of_same_size?(arr)
arr.map(&:size).uniq.size == 1
end
另一种解决方案:
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
当它发现元素与第一个元素的大小不同时,它会立即返回false。
有最佳方法吗? (当然......)
答案 0 :(得分:13)
使用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
答案 1 :(得分:3)
答案 2 :(得分:2)
我喜欢toro2k的回答。我只是想添加将方法添加到数组类本身的可能性,并警告您不是数组但响应 size 方法的元素仍然可以返回true。 (编辑:如果为空数组则为false)
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
答案 3 :(得分:2)
只是为了它的乐趣,如果您选择扩展Array
,您可以采用更灵活的方式,例如实施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
这允许:
[[1,2], [5,6], [8,9]].same?(&:size)
或
[[1,2], [7,8], [5,6], [8,9]].same?(&:max)
或只是(默认会与==
进行比较)
[[1,2], [7,8], [5,6], [8,9]].same?
答案 4 :(得分:0)
一些基准:
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)
我的钱是使用Enumerable#all的类方法?通过toko2k
答案 5 :(得分:0)
如果处理非嵌套数组的数组,可以测试以确保矩阵是正方形。它将递归数组抛出窗口,但是很简洁。
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