Write a function (such as placeAt
) that takes an array of non-negative integers and an index that is a non-negative integer. It should place a 1 at the given index, possibly shifting other entries by one spot to vacate that spot, with 0's standing for empty spots.
- If the entry at the desired index is 0, fill it with a 1.
- Otherwise, look for the nearest 0 to the left of the index. Shift entries one spot left into that 0 to make room, then fill the index with a 1.
- If there's no 0 to the left, do the same going right.
- If neither is possible (i.e. if there is no 0), return the array unchanged.
The items are 0-indexed. Function name can be anything you want.
Examples:
(Letters stand for any positive integer values.)
[a, b, 0, c, d, 0] placeAt 2 // output [a, b, 1, c, d, 0] place 2 is 0, just fill
[a, b, 0, c, d, 0] placeAt 3 // output [a, b, c, 1, d, 0] place 3 is filled, shift items left
[a, b, 0, c, d, 0] placeAt 0 // output [1, a, b, c, d, 0] place 0 is filled, can't shift left, shift items right
[a, b, 0, c, d, 0] placeAt 1 // output [a, 1, b, c, d, 0] place 1 is filled, can't shift left, shift items right
[0, a, b, 0, c, d, 0] placeAt 2 // output [a, b, 1, 0, c, d, 0] place 2 is filled, shift items left
[0, a, b, 0, c, d, 0] placeAt 4 // output [0, a, b, c, 1, d, 0] place 4 is filled, shift items left (notice you keep shifting up until a 0)
[0, 2, 0, 2] placeAt 3 // output [0, 2, 2, 1] place 3 is filled, shift items left
This is a code golf challenge. The shortest entry at the end of 9 days wins.
0
? \$\endgroup\$[0, 2, 0, 2] placeAt 3
, is it legal to output[2, 0, 2, 1]
? Is the code required to actually be a function calledplaceAt
? Note that some languages don't exactly have functions. "Throw an exception" might also not apply to some languages; I'd suggest allowing an output indicating an error. \$\endgroup\$[2, 0, 2, 1]
is not a legal output, as you should always shift as few elements as possible, and you can name the function whatever you want. \$\endgroup\$