将 ruby​​ 数组的元素划分为精确数量的(几乎)大小相等的子数组 [英] Dividing elements of a ruby array into an exact number of (nearly) equal-sized sub-arrays

查看:25
本文介绍了将 ruby​​ 数组的元素划分为精确数量的(几乎)大小相等的子数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种方法将数组拆分为大小大致相等的确切数量的较小数组.任何人都有这样做的方法吗?

例如

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]组 = a.method_i_need(3)分组检查=>[[1,2,3,4,5], [6,7,8,9], [10,11,12,13]]

<块引用>

请注意,这与将数组分成多个块是一个完全不同的问题,因为a.each_slice(3).to_a 将产生 5 个组(不是我们希望的 3 个)并且最后一个组的大小可能与其他组完全不同:

[[1,2,3], [4,5,6], [7,8,9], [10,11,12], [13]] # 这里不需要.

本题预先指定了想要的chunk数量,每个chunk的大小最多相差1.

解决方案

您正在寻找 Enumerable#each_slice

a = [0, 1, 2, 3, 4, 5, 6, 7]a.each_slice(3) # =>#<Enumerator: [0, 1, 2, 3, 4, 5, 6, 7]:each_slice(3)>a.each_slice(3).to_a # =>[[0, 1, 2], [3, 4, 5], [6, 7]]

I need a way to split an array in to an exact number of smaller arrays of roughly-equal size. Anyone have any method of doing this?

For instance

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] 
groups = a.method_i_need(3)
groups.inspect
    => [[1,2,3,4,5], [6,7,8,9], [10,11,12,13]]

Note that this is an entirely separate problem from dividing an array into chunks, because a.each_slice(3).to_a would produce 5 groups (not 3, like we desire) and the final group may be a completely different size than the others:

[[1,2,3], [4,5,6], [7,8,9], [10,11,12], [13]]  # this is NOT desired here.

In this problem, the desired number of chunks is specified in advance, and the sizes of each chunk will differ by 1 at most.

解决方案

You're looking for Enumerable#each_slice

a = [0, 1, 2, 3, 4, 5, 6, 7]
a.each_slice(3) # => #<Enumerator: [0, 1, 2, 3, 4, 5, 6, 7]:each_slice(3)>
a.each_slice(3).to_a # => [[0, 1, 2], [3, 4, 5], [6, 7]]

这篇关于将 ruby​​ 数组的元素划分为精确数量的(几乎)大小相等的子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆