阵中每隔2个项目

时间:2012-11-02 13:39:00

标签: ruby

我需要一个ruby公式来创建一个整数数组。该数组必须是每隔两个数字,如下所示。

[2, 3, 6, 7, 10, 11, 14, 15, 18, 19...]

我已经阅读了很多关于如何做其他所有数字或倍数的内容,但我不确定实现我需要的最佳方法。

7 个答案:

答案 0 :(得分:3)

这是一种适用于任何阵列的方法。

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"]

答案 1 :(得分:3)

array = []
#Change 100000 to whatever is your upper limit
100000.times do |i|
  array << i if i%4 > 1
end

答案 2 :(得分:1)

此代码适用于任何起始编号到任何结束限制

i = 3
j = 19
x =[]
(i...j).each do |y|
  x << y if (y-i)%4<2
end
puts x

这应该有效

答案 3 :(得分:1)

为了好玩,使用懒惰的enumerables(需要Ruby 2.0或gem enumerable-lazy):

(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]

答案 4 :(得分:0)

这是一个适用于无限流的解决方案:

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

答案 5 :(得分:0)

Single Liner:

(0..20).to_a.reduce([0,[]]){|(count,arr),ele| arr << ele if count%4 > 1;
                                                           [count+1,arr] }.last

说明:

使用0,[] in count,arr vars

开始缩小外观

如果条件满足,则将当前元素添加到数组。块返回增量,arr用于下一次迭代。

我同意,虽然它不是一个单一的班轮,但看起来有点复杂。

答案 6 :(得分:0)

这是塞尔吉奥精彩答案的稍微更一般的版本

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]