如何将一个数组拆分成n个相等或接近相等的数组? [英] How to split an array into n equal or close to equal arrays?

查看:105
本文介绍了如何将一个数组拆分成n个相等或接近相等的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大数组,我想平均分成 n 个数组。

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


  • 我有100个元素的数组。我想将其平均分成4个数组。这将给我4个数组,每个数组包含25个元素。

  • 我有一个包含100个元素的数组。我想将其平均分成3个数组。由于无法将其均匀地划分为子数组,因此我需要2个33个元素的数组和34个元素的一个数组。

  • 我有2个元素的数组。我想将其平均分成4个数组。由于我无法平均分割它,并且某些数组将为空,因此我想要2个数组,每个数组包含1个元素和2个空数组。

我尝试使用 each_slice ,但这只能根据传递给它的number参数将数组切成小块。

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

我该怎么做?

推荐答案

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]]

这篇关于如何将一个数组拆分成n个相等或接近相等的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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