2012-11-02 58 views
0

我需要一個紅寶石公式來創建一個整數數組。該陣列必須是每隔2個數字如下。其他每個項目中的2個項目

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

我已經閱讀了很多關於我如何能做到每隔數或倍數,但我不知道,實現什麼,我需要的最佳途徑。

+0

的稍微普通版的陣列停止,或者您需要一個無限枚舉? – tokland

回答

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

爲什麼你需要把一個空白(_,idx)?它可以正常工作: def every_other_two arr arr.select.with_index do | idx | idx%4> 1 結束 結束 雖然好的棘手的解決方案。 +1 :) –

+0

你的版本是否也適用於我的第二個數組? –

+0

@ K.M.RakibulIslam:未來,請使用像http://pastie.org這樣的服務。在評論中發佈可讀代碼是不可能的。 –

1

此代碼適用於任何起始號碼給任何限制

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

這應該工作

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

爲了好玩,用慵懶的枚舉接口(需要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] 
0

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。

我同意,雖然它不是一個單一的班輪,但看起來有點複雜。

0

這裏是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] 
相關問題