我有一个子数组的数组:
arr = [["a", "b", "c"], ["a", "b"], ["a", "b", "c"], ["a", "c"],
["c", "v"], ["c", "f"], ["e", "a"], ["a", "b", "v"],
["a", "n", "c"], ["a", "b", "m"], ["a", "c"], ["a", "c", "g"]]
我希望将每个子数组的元素放入另一个数组中,但子数组大小之和必须小于或等于6。因此,我希望得到这样的结果。
[["a", "b", "c", "a", "b"], ["a", "b", "c", "a", "c"],
["c", "v", "c", "f", "e", "a"], ["a", "b", "v", "a", "n", "c"],
["a", "b", "m", "a", "c"], ["a", "c", "g"]]
我现在的代码是
stop = 0
new_arr = []
indexo = ""
arr.each_with_index do |x, index|
stop = stop + x.size
if stop <= 6
new_arr << x
indexo = index
end
end
我之所以卡在这里,是因为我的代码只取了前两个元素。原始数组有大约1000个子数组,而我的代码没有按那种形式进行分割。