Replacing all subsequences in a list

This seems to work.

bill = {-1, 1, -1, 1, 1, 1, -1, -1, -1, 1};
Flatten[SequenceReplace[bill, {-1, 1} :> {0, 1}]]

{0, 1, 0, 1, 1, 1, -1, -1, 0, 1}

I also include the output without Flatten, it might be of interest as to how it works. The documentation can be found here

{{0, 1}, {0, 1}, 1, 1, -1, -1, {0, 1}}

EDIT: Courtesy of @MarcoB and @Bob Hanlon:

 SequenceReplace[bill, {-1, 1} :> Sequence[0, 1]]

This is the solution I came up with. It should work with 10.1+


ReplacePart[list, 
 Rule[#, 0] & /@ First /@ SequencePosition[list, {-1, 1}]]

(* {0, 1, 0, 1, 1, 1, -1, -1, 0, 1} *)

The length of the Trace is 4. Oddly, considering its messy implementation, this is shorter than the length of the Trace for the solution in Titus's answer, which is 5.


Length@Trace@
  ReplacePart[list, 
   Rule[#, 0] & /@ First /@ SequencePosition[list, {-1, 1}]]
Length@Trace@SequenceReplace[list, {-1, 1} :> Sequence[0, 1]]

(* 4 *)
(* 5 *)

The solution is also somehow faster, this might be given due to the shorter length of the Trace. That would mean that it scales better than that of Titus's solution.


ReplacePart[list, 
   Rule[#, 0] & /@ First /@ SequencePosition[list, {-1, 1}]] // 
  RepeatedTiming // First
SequenceReplace[list, {-1, 1} :> Sequence[0, 1]] // 
  RepeatedTiming // First


(* 0.000034 *)
(* 0.000078 *)

Hope you find that this helps for the version that you are on.


Join[  #[[;; -2, 1]], # [[-1]] ] &@ (Partition[list, 2, 1, {1, 2}] /. {-1, 1} -> {0, 1})