我有一些在代码前面生成的不同长度的数组,由有序对的子数组组成。如果有多于一对,则输出为数组的数组。如果只有一对,则输出为单个数组。
什么是一种简单、一致的方法来转换输出,使其始终处于递归的一个级别,而无需编写过于狭窄的内容来测试确切的事件?现在我有:
output_array = [7, 5]
output_array = output_array.flatten.each_slice(2).to_a
=> [[7, 5]]
output_array = [[7, 5], [6, 2]]
output_array = output_array.flatten.each_slice(2).to_a
=> [[7, 5], [6, 2]]
最佳答案
检查内部元素是否为数组,如果不是,则将其插入到空数组中,虽然不那么可爱但速度更快。
oa1.first.kind_of?(Array) ? oa1 : [oa1]
Mudasobwa 请原谅我使用您出色的解决方案进行比较。
require 'benchmark'
n = 10_000
oa1 = [5,7]
oa2 = [[5,7],[6,8]]
c1 = c2 = c3 = 0
Benchmark.bm do |x|
x.report {
n.times do
c1 += oa1.flatten.each_slice(2).to_a.first.first \
+ oa2.flatten.each_slice(2).to_a.first.first
end
}
x.report {
n.times do
c2 += Hash[*oa1.flatten].to_a.first.first \
+ Hash[*oa2.flatten].to_a.first.first
end
}
x.report {
n.times do
c3 += (oa1.first.kind_of?(Array) ? oa1 : [oa1]).first.first \
+ (oa2.first.kind_of?(Array) ? oa2 : [oa2]).first.first \
end
}
end
puts "c1 = #{c1}, c2 = #{c2}, c3 = #{c3}"
给予
user system total real
0.063000 0.000000 0.063000 ( 0.071007)
0.062000 0.000000 0.062000 ( 0.056006)
0.016000 0.000000 0.016000 ( 0.008001)
c1 = 100000, c2 = 100000, c3 = 100000
关于ruby - 您如何保证数组具有最低级别的递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20184199/