Taken from this question at Stack Overflow. Thanks also to @miles and @Dada for suggesting test inputs that address some corner cases.
The challenge
Given an array of integer values, remove all zeros that are not flanked by some nonzero value.
Equivalently, an entry should be kept either if it's a nonzero or if it's a zero that is immediately close to a nonzero value.
The entries that are kept should maintain in the output the order they had in the input.
Example
Given
[2 0 4 -3 0 0 0 3 0 0 2 0 0]
the values that should be removed are marked with an x
:
[2 0 4 -3 0 x 0 3 0 0 2 0 x]
and so the output should be
[2 0 4 -3 0 0 3 0 0 2 0]
Rules
The input array may be empty (and then the output should be empty too).
Input and output formats are flexible as usual: array, list, string, or anything that is reasonable.
Code golf, fewest best.
Test cases
[2 0 4 -3 0 0 0 3 0 0 2 0 0] -> [2 0 4 -3 0 0 3 0 0 2 0]
[] -> []
[1] -> [1]
[4 3 8 5 -6] -> [4 3 8 5 -6]
[4 3 8 0 5 -6] -> [4 3 8 0 5 -6]
[0] -> []
[0 0] -> []
[0 0 0 0] -> []
[0 0 0 8 0 1 0 0] -> [0 8 0 1 0]
[-5 0 5] -> [-5 0 5]
[50 0] -> [50 0]
_2
instead of-2
? Quite a few languages use that format. \$\endgroup\$-0
? \$\endgroup\$[010 0 0 01 1]
? \$\endgroup\$