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$

2 Answers 2

4
$\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$
3
  • $\begingroup$ Seems this doesn't give the desired result? :) $\endgroup$ Commented Jun 15, 2018 at 8:01
  • $\begingroup$ @atoman, fixed now. $\endgroup$ Commented Jun 15, 2018 at 8:02
  • $\begingroup$ Looks nice!! thx:) $\endgroup$ Commented Jun 15, 2018 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$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.