Consider a list containing zeros and ones:
list = {0,0,0,1,1,1,0,0,0,0,0,0,1,1,1,1,0,0,0,0,1,0,0,0,1,1,1,1};
I would like to have a function that takes the above list as input and returns another list, which has the regions containing 1
's either shrunk by one to the left and right, or extended by one to left and right. I.e.:
extend[list]
{0,0,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,0,0,1,1,1,0,1,1,1,1,1}
shrink[list]
{0,0,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0}
I know how to implement this in terms of a trivial Do
loop, but I suspect that there might be a different quick and elegant solution. Is there a neat way to do this?
Update
Here is my ugly Frankenstein (p=1
to extend p=0
to shrink):
extendORshrink[x_,p_] := Block[{inp, tmp},
inp = x; tmp = {};
Do[If[x[[i]] =!= x[[i + 1]], AppendTo[tmp, {i, i + 1}]];, {i, 1, Length[x] - 1}];
Do[inp[[tmp[[i, 1]]]] = p; inp[[tmp[[i, 2]]]] = p;, {i, 1, Length[tmp]}];
inp
]