tl;dr我想用除以5的结果做一个数组:
20 => [5,5,5,5]
16 => [5,5,5,1]
7 => [5,2]
我目前的实现很简单,但规模太大了。如何使它变得更简单、更短?
max_count = 5
total_count = input_value
count_array = []
div = total_count / max_count
mod = total_count % max_count
div.times { count_array << max_count }
count_array << mod unless mod == 0
- 您不需要
total_count
div.times { count_array << max_count }
就是[max_count] * count_array
- 使用splat,我们可以进一步简化它
max_count = 5
[*[max_count] * (input_value / max_count), input_value % max_count] - [0]
或者,使用divmod
max_count = 5
n, mod = input_value.divmod(max_count)
[*[max_count] * n, mod] - [0]
最后一行也可以写成:
(Array.new(n) { max_count } << mod) - [0]
或者正如Stefan在评论中建议的那样,使用Numeric#nonzero?:
Array.new(n, max_count).push(*mod.nonzero?)
还有一个选项:
d = 5
n = 24
Array.new(n/d){d}.tap{ |a| a << n%d if (n%d).nonzero? }
#=> [5, 5, 5, 5, 4]
您也可以尝试一下。
max=5
num=48
q, r=num.divmod(max) # => [9, 3]
Array.new.fill(max, 0, q).push(r.nonzero?).compact
# => [5, 5, 5, 5, 5, 5, 5, 5, 5, 3]
这个怎么样?
[20].tap{|a| a.push(5, a.pop - 5) while a.last > 5} # => [5, 5, 5, 5]
[16].tap{|a| a.push(5, a.pop - 5) while a.last > 5} # => [5, 5, 5, 1]
[7] .tap{|a| a.push(5, a.pop - 5) while a.last > 5} # => [5, 2]