List, map function based on a condition
Using ReplaceRepeated
(//.
) and pattern matching:
input //. {{x___, 0, 1, y___} :> {x, 0.5, 1, y}, {x___, 1, 0, y___} :> {x, 1, 0.5, y}}
{{0, 0, 0, 0.5, 1, 1, 1, 0.5, 1, 0.5, 0, 0.5, 1, 1, 0.5, 1, 0.5, 0, 0.5, 1, 0.5, 1}, {0.5, 1, 0.5, 1, 0.5, 0.5, 1, 0.5, 0, 0, 0, 0.5, 1, 1, 0.5, 1, 0.5, 0, 0.5, 1, 0.5, 1}, {1, 1, 0.5, 0.5, 1, 1, 1, 0.5, 0, 0, 0, 0.5, 1, 1, 0.5, 1, 0.5, 0, 0.5, 1, 0.5, 1}}
Note that there is a slight difference between this and your suggested output, highlighted in bold. As @Nasser received this result by his method as well, I suspect that the original suggested output
was in error.
You can also use a combination of SequenceReplace
and FixedPoint
:
f = Map[SequenceReplace[{{0, 1} -> Sequence[.5, 1], {1, 0} -> Sequence[1, .5]}]],
FixedPoint[f, input]
{{0, 0, 0, 0.5, 1, 1, 1, 0.5, 1, 0.5, 0, 0.5, 1, 1, 0.5, 1, 0.5, 0, 0.5, 1, 0.5, 1},
{0.5, 1, 0.5, 1, 0.5, 0.5, 1, 0.5, 0, 0, 0, 0.5, 1, 1, 0.5, 1, 0.5, 0, 0.5, 1, 0.5, 1},
{1, 1, 0.5, 0.5, 1, 1, 1, 0.5, 0, 0, 0, 0.5, 1, 1, 0.5, 1, 0.5, 0, 0.5, 1, 0.5, 1}}
You can also use Nest
in place of FixedPoint
:
Nest[f , input, 2] == %
True
For a rewriting problem, use rewriting explicitly:
input //. {
{x___, 0, 1, y___} -> {x, 0.5, 1, y},
{x___, 1, 0, y___} -> {x, 1, 0.5, y}
}
(*
{{0, 0, 0, 0.5, 1, 1, 1, 0.5, 1, 0.5, 0, 0.5, 1, 1, 0.5, 1, 0.5, 0, 0.5, 1, 0.5, 1},
{0.5, 1, 0.5, 1, 0.5, 0.5, 1, 0.5, 0, 0, 0, 0.5, 1,1, 0.5, 1, 0.5, 0, 0.5, 1, 0.5, 1},
{1, 1, 0.5, 0.5, 1, 1, 1, 0.5, 0, 0, 0, 0.5, 1, 1, 0.5, 1, 0.5, 0, 0.5, 1, 0.5, 1}}
*)