整数到块数组

时间:2018-08-03 05:27:31

标签: ruby range

我需要将一个整数变成一个间隔数组。例如,

number_to_steps(number: 10, step: 3)
# => [[0, 2], [3, 5], [6, 8], [9, 9]]

number_to_steps(number: 7, step: 2)
# => [[0, 1], [2, 3], [4, 5], [6, 6]]

number_to_steps(number: 8, step: 2)
# => [[0, 1], [2, 3], [4, 5], [6, 7]]

我尝试过:

def number_to_ranges(number:, size:)
    chunks = ((number - 1) / size.to_f).ceil

    (0..chunks - 1).map do |index|
      from = index * size
      to = (index + 1) * size - 1

      [ from, to > number ? number : to ]
    end
  end

但是它不能正常工作。例如,

number_to_ranges(number: 14, step: 4)
[[0, 3], [4, 7], [8, 11], [12, 14]]

不应转到14。

有什么主意吗?

3 个答案:

答案 0 :(得分:7)

(您的方法)的另一种选择是使用each_slice

def number_to_steps(number:, step:)
  (0...number).each_slice(step).map { |arr| [arr.first, arr.last] }
end

测试:

number_to_steps(number: 10, step: 3)
 #=> [[0, 2], [3, 5], [6, 8], [9, 9]]

number_to_steps(number: 7, step: 2)
 #=> [[0, 1], [2, 3], [4, 5], [6, 6]]

number_to_steps(number: 8, step: 2)
 #=> [[0, 1], [2, 3], [4, 5], [6, 7]]

答案 1 :(得分:7)

console.log

答案 2 :(得分:2)

您需要在两个地方更改方法number_to_ranges

  • 计算chunks的数量时,请将number - 1更改为number
  • 找到块的最后一个元素时,请执行number - 1而不是number

这是最终代码的样子:

def number_to_ranges(number:, size:)
  chunks = (number / size.to_f).ceil

  (0...chunks).map do |index|
    from = index * size
    to = (index + 1) * size - 1

    [from, [to, number - 1].min]
  end
end

number_to_ranges(number: 10, size: 3)
 => [[0, 2], [3, 5], [6, 8], [9, 9]] 

number_to_ranges(number: 7, size: 2)
 => [[0, 1], [2, 3], [4, 5], [6, 6]] 

number_to_ranges(number: 8, size: 2)
 => [[0, 1], [2, 3], [4, 5], [6, 7]] 

number_to_ranges(number: 14, size: 4)
 => [[0, 3], [4, 7], [8, 11], [12, 13]]