Home Distribute items into containers in twos - Rails
Reply: 0

Distribute items into containers in twos - Rails

user1311
1#
user1311 Published in May 22, 2018, 12:27 am

I have a list of 10 items -- it is an array of hashes.

[{ id: 1, name: 'one'}, { id: 2, name: 'two' } .. { id: 10, name: 'ten' }]

I also have a random number of containers -- let's say 3, in this case. These containers are hashes with array values.

{ one: [], two: [], three: [] }

What I want to do, is iterate over the containers and drop 2 items at a time resulting in:

{ 
   one: [{id:1}, {id:2}, {id:7}, {id:8}], 
   two: [{id:3}, {id:4}, {id:9}, {id:10}], 
   three: [{id:5}, {id:6}] 
}

Also, if the item list is an odd number (11), the last item is still dropped into the next container.

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

note: the hashes are snipped here so it's easier to read.

My solution is something like this: (simplified)

x = 10
containers = { one: [], two: [], three: [] }

until x < 1 do
    containers.each do |c|
        c << 'x'
        c << 'x'
    end
    x -= 2
end

puts containers

I'm trying to wrap my head around how I can achieve this but I can't seem to get it to work.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.309246 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO