如何在ruby中获得偶数组?

亚伯兰

假设我想根据不同计数的记录集合获得一定数量的偶数组。这怎么可能?

我正在寻找一种方法 objects.in_x_even_groups(4)

卡里·斯沃夫兰

我假设:

  • 元素应保持有序;
  • l-s是最小化,其中l是最大组s的大小, 是最小组的大小;
  • 组大小没有增加。

l-s将至多1

def group_em(arr, ngroups)
  n_per_group, left_over = arr.size.divmod(ngroups)
  cum_off = 0
  ngroups.times.map do |i|
    n = n_per_group + (i < left_over ? 1 : 0)
    a = arr[cum_off, n]
    cum_off += n
    a     
  end
end

arr = [1, 2, 3, 4, 5, 6, 7]
(1..7).each { |m| puts "ngroups=#{m}: #{group_em(arr, m)}" }
ngroups=1: [[1, 2, 3, 4, 5, 6, 7]]
ngroups=2: [[1, 2, 3, 4], [5, 6, 7]]
ngroups=3: [[1, 2, 3], [4, 5], [6, 7]]
ngroups=4: [[1, 2], [3, 4], [5, 6], [7]]
ngroups=5: [[1, 2], [3, 4], [5], [6], [7]]
ngroups=6: [[1, 2], [3], [4], [5], [6], [7]]
ngroups=7: [[1], [2], [3], [4], [5], [6], [7]]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章