Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I would to match a pattern

 p1 = 0,0,1,0,0

to the elements in listA. The elements are a boolean sequence that may look like this

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

Every where p1 matches the sequence I want to change that part into

 p2 = .5, .5, 1, .5, .5

that will change listA into

 {{.5, .5, 1, .5, .5, 1, 0, 1, 1, .5, .5, 1, .5, .5},   {0, 0, .5, .5, 1, .5, .5, .5, .5, 1, .5, .5, 0, 0}}

Thanks!

share|improve this question
    
What with overlapping, {0,0,1,0,0,1,0,0}? –  Kuba Aug 16 '13 at 22:55
1  
Note that you cannot assign a raw sequence such as p1 = 0,0,1,0,0. You can use Sequence 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. –  Mr.Wizard Aug 16 '13 at 23:18
    
@ Mr.Wizard. Thank You! I have been studying the code and I have two questions. Why is the first argument {s} passed in wrapped in a List? Also do I have this right, The function will only execute with condition Length[List[s]] == Length[r]? –  spaceKnot Aug 19 '13 at 4:17
add comment

1 Answer 1

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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