首页 > 解决方案 > 从Ruby中的整数除法制作数组的正确方法

问题描述

tl;博士我想从除以 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

标签: arraysrubyinteger

解决方案


  1. 你不需要total_count
  2. div.times { count_array << max_count }[max_count] * count_array
  3. 使用 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?)

推荐阅读