检查数组的元素大小相同
有没有一种最好有效的方法来检查数组的元素是否大小相同?
[[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。
有最佳方法吗? (当然…)
那么使用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
再提供一个单线:
你可以使用chunk
和one?
[[1,2], [3,4], [7,8], [5,6]].chunk(&:size).one?
我喜欢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
只是为了它的乐趣,如果扩展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?
一些基准:
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
如果处理非嵌套数组的数组,则可以测试以确保矩阵是正方形。 它将窗口中的递归数组抛出,但有点简洁。
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