从Ruby中的整数除法制作数组的正确方法

时间:2018-11-22 20:45:43

标签: arrays ruby integer

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

4 个答案:

答案 0 :(得分:4)

  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?)

答案 1 :(得分:0)

更多选择:

d = 5
n = 24
Array.new(n/d){d}.tap{ |a| a << n%d if (n%d).nonzero? }
#=> [5, 5, 5, 5, 4]

答案 2 :(得分:0)

您也可以尝试。

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]

答案 3 :(得分:0)

那呢?

 'function_score' => [
       'query' => $query,
           'score_mode' => 'sum',
              'functions' => [[
                'script_score' => [
                 'script' => [
                   'params' => ['listing' => [123 => 123, 456 => 456]],
    'source' => "(params.listing.contains(doc['id'].value) ? Math.pow(3, 3) : 0)",
                            ],
                        ],
                    ]],
                ],