How do I replace each value in run with the integer preceding the run

Viewed 513

Using Mathematica, I have a list:

l={0,0,0,1,2,0,0,0,1,0,0,0,2,0,0,0}

I want to apply a function to the above list to obtain the following:

{0,0,0,1,2,2,2,2,1,1,1,1,2,2,2,2}

Essentially I want to replace the runs of 0 values with runs of the same length, but using the value of the positive integer just preceding each run of 0s.

I thought I could do this easily with FoldList, but I can't see my way through to a solution.

Many thanks.

3 Answers
Related