如何将数组拆分为n等于或接近相等的数组?

时间:2021-06-04 19:36:18

I have a large array that I would like to split evenly into n arrays.

我有一个大型数组,我想将其均匀地分成n个数组。

  • I have an array of 100 elements. I would like to split it evenly into 4 arrays. This would give me 4 arrays of 25 elements each.
  • 我有一个包含100个元素的数组。我想将它平均分成4个数组。这将给我4个阵列,每个25个元素。
  • I have an array of 100 elements. I would like to split it evenly into 3 arrays. Since I cannot evenly split it into the sub-arrays, then I want something like 2 arrays of 33 elements and one array of 34 elements.
  • 我有一个包含100个元素的数组。我想将它平均分成3个数组。由于我无法将其均匀地分割为子数组,因此我需要类似于3个33个元素的数组和一个34个元素的数组。
  • I have an array of 2 elements. I would like to split it evenly into 4 arrays. Since I cannot split it evenly and some arrays will be empty, then I want something like 2 arrays of 1 element and 2 empty arrays.
  • 我有一个包含2个元素的数组。我想将它平均分成4个数组。由于我不能均匀地拆分它并且一些数组将是空的,所以我想要2个1元素和2个空数组的数组。

I tried using each_slice, but that only slices the array into small parts based on the number argument passed to it.

我尝试使用each_slice,但只根据传递给它的数字参数将数组切成小部分。

How can I do this?

我怎样才能做到这一点?

1 个解决方案

#1


7  

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

a.group_by.with_index{|_, i| i % 2}.values
# => [[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]

a.group_by.with_index{|_, i| i % 3}.values
# => [[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]]

a.group_by.with_index{|_, i| i % 4}.values
# => [[1, 5, 9], [2, 6, 10], [3, 7], [4, 8]]

a.group_by.with_index{|_, i| i % 5}.values
# => [[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]

a.group_by.with_index{|_, i| i % 6}.values
# => [[1, 7], [2, 8], [3, 9], [4, 10], [5], [6]]

#1


7  

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

a.group_by.with_index{|_, i| i % 2}.values
# => [[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]]

a.group_by.with_index{|_, i| i % 3}.values
# => [[1, 4, 7, 10], [2, 5, 8], [3, 6, 9]]

a.group_by.with_index{|_, i| i % 4}.values
# => [[1, 5, 9], [2, 6, 10], [3, 7], [4, 8]]

a.group_by.with_index{|_, i| i % 5}.values
# => [[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]

a.group_by.with_index{|_, i| i % 6}.values
# => [[1, 7], [2, 8], [3, 9], [4, 10], [5], [6]]