我需要一个红宝石公式来创建一个整数数组。该阵列必须是每隔2个数字如下。其他每个项目中的2个项目
[2, 3, 6, 7, 10, 11, 14, 15, 18, 19...]
我已经阅读了很多关于我如何能做到每隔数或倍数,但我不知道,实现什么,我需要的最佳途径。
我需要一个红宝石公式来创建一个整数数组。该阵列必须是每隔2个数字如下。其他每个项目中的2个项目
[2, 3, 6, 7, 10, 11, 14, 15, 18, 19...]
我已经阅读了很多关于我如何能做到每隔数或倍数,但我不知道,实现什么,我需要的最佳途径。
这里的任何阵列上工作的方法。
def every_other_two arr
arr.select.with_index do |_, idx|
idx % 4 > 1
end
end
every_other_two((0...20).to_a) # => [2, 3, 6, 7, 10, 11, 14, 15, 18, 19]
# it works on any array
every_other_two %w{one two three four five six} # => ["three", "four"]
为什么你需要把一个空白(_,idx)?它可以正常工作: def every_other_two arr arr.select.with_index do | idx | idx%4> 1 结束 结束 虽然好的棘手的解决方案。 +1 :) –
你的版本是否也适用于我的第二个数组? –
@ K.M.RakibulIslam:未来,请使用像http://pastie.org这样的服务。在评论中发布可读代码是不可能的。 –
此代码适用于任何起始号码给任何限制
i = 3
j = 19
x =[]
(i...j).each do |y|
x << y if (y-i)%4<2
end
puts x
这应该工作
array = []
#Change 100000 to whatever is your upper limit
100000.times do |i|
array << i if i%4 > 1
end
下面是一个具有无限流的有效的解决方案:
enum = Enumerator.new do |y|
(2...1/0.0).each_slice(4) do |slice|
slice[0 .. 1].each { |n| y.yield(n) }
end
end
enum.first(10) #=> [2, 3, 6, 7, 10, 11, 14, 15, 18, 19]
enum.each do |n|
puts n
end
为了好玩,用慵懒的枚举接口(需要Ruby 2.0或宝石枚举懒):
(2..Float::INFINITY).step(4).lazy.map(&:to_i).flat_map { |x| [x, x+1] }.first(8)
#=> => [2, 3, 6, 7, 10, 11, 14, 15]
Single Liner:
(0..20).to_a.reduce([0,[]]){|(count,arr),ele| arr << ele if count%4 > 1;
[count+1,arr] }.last
说明:
启动降低外观与0,[]中的计数,ARR乏如果条件成立
当前元素添加到阵列。 Block返回下一次迭代的增量和arr。
我同意,虽然它不是一个单一的班轮,但看起来有点复杂。
这里是Sergio的罚款答案
module Enumerable
def every_other(slice=1)
mod = slice*2
res = select.with_index { |_, i| i % mod >= slice }
block_given? ? res.map{|x| yield(x)} : res
end
end
irb> (0...20).every_other
=> [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
irb> (0...20).every_other(2)
=> [2, 3, 6, 7, 10, 11, 14, 15, 18, 19]
irb> (0...20).every_other(3)
=> [3, 4, 5, 9, 10, 11, 15, 16, 17]
irb> (0...20).every_other(5) {|v| v*10 }
=> [50, 60, 70, 80, 90, 150, 160, 170, 180, 190]
的稍微普通版的阵列停止,或者您需要一个无限枚举? – tokland