Your basic (simple, but inefficient) method is to use ReplaceRepeated
:
start =
{{0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0}, {0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0}};
start //. {a___, 0, 0, 1, 0, 0, b___} :> {a, .5, .5, 1, .5, .5, b}
{{0.5, 0.5, 1, 0.5, 0.5, 1, 0, 1, 1, 0.5, 0.5, 1, 0.5, 0.5},
{0, 0, 0.5, 0.5, 1, 0.5, 0.5, 0.5, 0.5, 1, 0.5, 0.5, 0, 0}}
Your next level of optimization is to find all the positions first, and then replace.
I'll use a nice ReplaceList
method from Jan Pöschko for the sequence position step.
f[{s__}, r_List][v_List] /; Length[{s}] == Length[r] :=
Module[{m = v, n = Length[{s}]},
m[[# + 1 ;; # + n]] = r; & /@
ReplaceList[v, {a___, s, ___} :> Length[{a}]];
m
]
p1 = {0, 0, 1, 0, 0};
p2 = {.5, .5, 1, .5, .5};
f[p1, p2] /@ start
{{0.5, 0.5, 1, 0.5, 0.5, 1, 0, 1, 1, 0.5, 0.5, 1, 0.5, 0.5},
{0, 0, 0.5, 0.5, 1, 0.5, 0.5, 0.5, 0.5, 1, 0.5, 0.5, 0, 0}}
For ultimate optimization you would use a faster sequence position function such as seqposCB
from Leonid Shifrin posted in position of sequence of elements in list.
For a literal pattern as in this example the function SequencePosition
introduced in 10.1.0 provides a much faster method than ReplaceList
shown above.
f2[s_List, r_List][v_List] /; Length[s] == Length[r] :=
Module[
{m = v, n = Length[s]}, m[[# ;; #2]] = r; & @@@ SequencePosition[v, s];
m
]
rand = RandomInteger[1, 50000];
AbsoluteTiming[r1 = f[p1, p2][rand];] // First
AbsoluteTiming[r2 = f2[p1, p2][rand];] // First
r1 === r2
0.551052
0.00407597
True
{0,0,1,0,0,1,0,0}
? $\endgroup$p1 = 0,0,1,0,0
. You can useSequence
e.g.p1 = Sequence[0,0,1,0,0]
but most of the time it is easier to just work with lists as shown in my answer. $\endgroup${s}
passed in wrapped in aList
? Also do I have this right, The function will only execute with conditionLength[List[s]] == Length[r]
? $\endgroup$