I have a row of powerful magnets and a bunch of metal objects between them. Where will the magnets pull them?
Your input is an array of non-negative integers, which will contain at least one
You can use any reasonable format.
0s of the array represent empty space, and the
1s represent fixed magnets.
All other numbers are metal objects, which are pulled by the magnets.
Every object gets pulled towards the nearest magnet (if there's a tie, the object is pulled to the right), and it travels in that direction until it hits the magnet or another object.
In the end, all the objects have clustered around the magnets.
The order of the objects is preserved.
Your output is the array where every object has been pulled as close to the nearest magnet as possible. It should have the same format as the input.
Consider the array
2 gets pulled towards the first pair of magnets, as does the second
3 has a magnet four steps away in both directions, so it gets pulled to the right.
5 also gets pulled to the right, and it goes between the
3 and the magnet.
The correct output is
Rules and scoring
You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed.
[0,1,0] -> [0,1,0] [1,0,2,0,0,1,0] -> [1,2,0,0,0,1,0] [7,0,5,0,0,1,0] -> [0,0,0,7,5,1,0] [1,0,3,0,1,0,3,0,1] -> [1,0,0,3,1,0,0,3,1] [1,0,0,0,0,0,0,7,3] -> [1,7,3,0,0,0,0,0,0] [1,2,3,4,5,6,7,8,9,10,11,0,0,0,1] -> [1,2,3,4,5,6,7,0,0,0,8,9,10,11,1] [12,3,0,0,1,0,1,3,0,0,6,12,0,0,0,1] -> [0,0,12,3,1,0,1,3,6,0,0,0,0,0,12,1]