gpt4 book ai didi

arrays - 按长度均匀排序数组项的 Ruby 数组

转载 作者:数据小太阳 更新时间:2023-10-29 07:54:43 25 4
gpt4 key购买 nike

在 Ruby 中,如何对数组进行排序,使其项目(也是数组)按长度大小排列,而不仅仅是按长度升序/降序排序。

我想使数组项均匀分布,以便有一些包含大量对象的项与较小的数组混合在一起。

例如,我有一个包含数组项的数组,其中包含 comment 中显示的对象数。为了清楚起见,我将它们分成几 block 并计算了它们的总大小(参见下面的动机)。

[
# chunk 1, inner total length 5
[{...}], # 2
[{...}], # 1
[{...}], # 1
[{...}], # 1
# chunk 2, inner total length 11
[{...}], # 2
[{...}], # 2
[{...}], # 3
[{...}], # 4
# chunk 3, inner total length 9
[{...}], # 3
[{...}], # 3
[{...}], # 1
[{...}], # 2
# chunk 4, inner total length 15
[{...}], # 4
[{...}], # 3
[{...}], # 4
[{...}], # 4
]

我想排列数组,使其看起来更像下面这样。注意:此示例将它们从小到大排序 (1..4),但这不是必需的。我只想将它们分块,以便内部数组的累积长度具有可比性。

[
# chunk 1, inner total length 10
[{...}], # 1
[{...}], # 2
[{...}], # 3
[{...}], # 4
# chunk 2, inner total length 10
[{...}], # 1
[{...}], # 2
[{...}], # 3
[{...}], # 4
# chunk 3, inner total length 10
[{...}], # 1
[{...}], # 2
[{...}], # 3
[{...}], # 4
# chunk 4, inner total length 10
[{...}], # 1
[{...}], # 2
[{...}], # 3
[{...}], # 4
]

我这样做的动机是将外部数组切分,以便我可以并行处理内部数组。我不希望其中一个并行进程获得一片小块,而另一个进程获得一片非常大的 block 。

注意:我知道我将有 4 个并行进程,这样可能有助于了解如何在数组中排列 block 。谢谢!

最佳答案

根据我对 OP 的评论,我将使用该算法获得大致均匀的大小分布:

unchunked_data = [
[{...}],
[{...}],
[{...}],
[{...}],
[{...}],
[{...}],
[{...}],
[{...}]
]

sorted_data = unchunked_data.sort_by(&:size)
grouped_data = sorted_data.each_with_index.group_by { |_, index| index % 4 }

grouped_data.each do |process_index, data|
# each_with_index would put data in an array with its index in sorted_data. Calling map(&:first) removes that index.
data_without_index = data.map(&:first)
send_data_to_process(process_index, data_without_index)
end

如果数据与 OP 的示例中显示的一样,则会产生完美的分布。


根据评论中的讨论,您可以取回单个数组中的所有数据,如原始格式但使用此方法分组,方法是:

grouped_data.values.flatten(1)

关于arrays - 按长度均匀排序数组项的 Ruby 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56872452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com