我需要将一个整数变成一个间隔数组。例如,
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。
有什么主意吗?
答案 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]]