我有一个包含10个项目的列表--这是一个散列数组。
[{ id: 1, name: 'one'}, { id: 2, name: 'two' } .. { id: 10, name: 'ten' }]我也有一个随机数量的容器--比如说3,在这个例子中。这些容器是带有数组值的散列。
{ one: [], two: [], three: [] }我想要做的是反复遍历容器,每次丢弃2项,结果如下:
{
one: [{id:1}, {id:2}, {id:7}, {id:8}],
two: [{id:3}, {id:4}, {id:9}, {id:10}],
three: [{id:5}, {id:6}]
}另外,如果项目列表是奇数(11),则最后一个项目仍然被放入下一个容器中。
{
one: [{id:1}, {id:2}, {id:7}, {id:8}],
two: [{id:3}, {id:4}, {id:9}, {id:10}],
three: [{id:5}, {id:6}, {id:11}]
}注意:散列是在这里剪短的,所以更容易读懂。
我的解决方案是这样的:(简化)
x = 10
containers = { one: [], two: [], three: [] }
until x < 1 do
containers.each do |c|
c << 'x'
c << 'x'
end
x -= 2
end
puts containers我正试图思考如何实现这一目标,但我似乎无法让它发挥作用。
发布于 2018-02-14 08:46:25
循环-知更鸟成对分布到三个箱子:
bins = 3
array = 10.times.map { |i| i + 1 }
# => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
array.
each_slice(2). # divide into pairs
group_by. # group into bins
with_index { |p, i| i % bins }. # round-robin style
values. # get rid of bin indices
each(&:flatten!) # join pairs in each bin完全不同的方法,按顺序填充垃圾桶:
base_size, bins_with_extra = (array.size / 2).divmod(bins)
pos = 0
bins.times.map { |i|
length = 2 * (base_size + (i < bins_with_extra ? 1 : 0)) # how much in this bin?
array[pos, length].tap { pos += length } # extract and advance
}
# => [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]如果你真的需要把这个放进哈希里,
Hash[%i(one two three).zip(binned_array)]
# => {:one=>[1, 2, 7, 8], :two=>[3, 4, 9, 10], :three=>[5, 6]}斯特凡·波奇曼( Stefan Pochmann)暗示的可爱(但很可能不是表演性的)解决方案:
bins.times.with_object(array.to_enum).map { |i, e|
Array.new(2 * (base_size + (i < bins_with_extra ? 1 : 0))) { e.next }
}发布于 2018-02-14 09:31:12
这只是为了展示一种不同的方法(我可能不会亲自使用这个方法)。
给定一个项数组和容器散列:
items = (1..10).to_a
containers = { one: [], two: [], three: [] }您可以对数组进行dup (以避免修改原始数组),并在散列中构建cycle的each_value枚举器:
array = items.dup
enum = containers.each_value.cycle使用上述方法,您可以从数组中shift 2项,并将其push到next容器中--数组为emtpy?。
enum.next.push(*array.shift(2)) until array.empty?结果:
containers
#=> {:one=>[1, 2, 7, 8], :two=>[3, 4, 9, 10], :three=>[5, 6]}发布于 2018-02-14 08:29:57
您可以使用Enumerable#each_slice在3s中遍历从0到10的范围,然后追加到数组中:
containers = [
[],
[],
[]
]
(1...10).each_slice(3) do |slice|
containers[0] << slice[0]
containers[1] << slice[1]
containers[2] << slice[2]
end
p containers
# [[1, 4, 7], [2, 5, 8], [3, 6, 9]]https://stackoverflow.com/questions/48782584
复制相似问题