# All possible pattern match and replacement

Given a list, how to get all possible new lists replacing a matched pattern with a new pattern (every time only one replacement)?

For example, I have a list like this {0, 1, 0, 1}. I want to first find all the {0, 1} in it. Then each time I replaced one and only one of them with {1, 0} to get a new list. So in this example the result should be {{1, 0, 0, 1}, {0, 1, 1, 0}}, each sublist of which is a list replacing one of the matched pattern {0, 1} with {1, 0}.

I try {0, 1, 0, 1} /. {x___, PatternSequence[0, 1], y___} -> {x, 1, 0, y} but this only gives one list {1, 0, 0, 1}, not whole possible lists.

You need to use ReplaceList:

ReplaceList[expr, rules]
attempts to transform the entire expression expr by applying a rule or list of rules in all possible ways, and returns a list of the results obtained.

lst = {0, 1, 0, 1};

ReplaceList[{x___, PatternSequence[0, 1], y___} :> {x, 1, 0, y}] @ lst


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

• Seems this doesn't give the desired result? :) Jun 15, 2018 at 8:01
• @atoman, fixed now.
– kglr
Jun 15, 2018 at 8:02
• Looks nice!! thx:) Jun 15, 2018 at 8:18

Table[ReplacePart[#,
Thread[SequencePosition[#, {0, 1}][[i]] -> {1, 0}]], {i,
Length[SequencePosition[#, {0, 1}]]}] &@{0, 1, 0, 1}


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

another test

Table[ReplacePart[#,
Thread[SequencePosition[#, {0, 1}][[i]] -> {1, 0}]], {i,
Length[SequencePosition[#, {0, 1}]]}] &@{0, 1, 0, 1, 1, 0, 1}


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