2
$\begingroup$

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.

$\endgroup$
3
$\begingroup$

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}}

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

My answer may be verbose:

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}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.