Background
I have a row of powerful magnets and a bunch of metal objects between them. Where will the magnets pull them?
Input
Your input is an array of non-negative integers, which will contain at least one 1
.
You can use any reasonable format.
The 0
s of the array represent empty space, and the 1
s 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.
Output
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.
Example
Consider the array
[0,0,2,0,1,1,0,2,0,3,0,5,0,1,0]
The leftmost 2
gets pulled towards the first pair of magnets, as does the second 2
.
The 3
has a magnet four steps away in both directions, so it gets pulled to the right.
The 5
also gets pulled to the right, and it goes between the 3
and the magnet.
The correct output is
[0,0,0,2,1,1,2,0,0,0,0,3,5,1,0]
Rules and scoring
You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed.
Test cases
[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]