A general way with patterns, that is pretty efficient and of linear complexity. (@halirutan's is also easily adapted to general patterns). Here pat
should be of the form {pat1, lookahead} -> replacement
):
seqRep[list_, pat_] :=
(Replace[Partition[list, 2, 1], {pat, {x_, y_} :> x}, {1}]) ~Append~ Last[list]
Example:
SeedRandom[1];
list = RandomInteger[{-1, 0}, 10]
(* {0, 0, -1, 0, -1, -1, -1, 0, -1, 0} *)
seqRep[list, {0, -1} -> 1]
(* {0, 1, -1, 1, -1, -1, -1, 1, -1, 0} *)
A fast way, that like others works on the OP's example of a list of integers. Its speed comes from auto-parallelization:
cf = Compile[{{x, _Integer}, {y, _Integer}},
If[x == 0 && y == -1, 1, x],
RuntimeAttributes -> {Listable}, Parallelization -> True,
RuntimeOptions -> "Speed", CompilationTarget -> "C"
]
Usage:
cf[Most@list, Rest@list]~Append~Last[list]
(* {0, 1, -1, 1, -1, -1, -1, 1, -1, 0} *)
As far as speed, on a list of 10^6
integers, the Replace
method took 0.42 sec., the compiled method took 0.051 sec., @ybeltukov's UnitStep
method took 0.071 sec., and Simon Wood's method took 0.071 sec.