4
$\begingroup$

For example, {{1,2,3},{1,2,3,1,2,3,4,5}}with pattern {1,_,3}is transformed to {{Style[1, Red], 2, Style[3, Red]}, {Style[1, Red], 2, Style[3, Red], Style[1, Red], 2, Style[3, Red], 4, 5}}enter image description here

Also the pattern could be things like {2,_,4,_,6}.

The solutions I can found either require an exact position, or highlight the complete part that matches the pattern (highlights all 1,2,3 in this example).And I have used Select to make sure the list contains this pattern.

How can I achieve this?

Update:

Based on Kuba and Jinxed's answer, I wrote the following code:

color[seq_, pat_] := Module[{i, lst = seq}, i = 1; pattlst = Prepend[Append[ pat /. (Verbatim[_] :> (ToExpression[ "temp$" <> ToString[i++] <> "_"])), last___], first___]; i = 1; target = Prepend[Append[ pat /. (Verbatim[_] :> (ToExpression["temp$" <> ToString[i++]])), last], first]; target = MapAt[Style[#, Red, Bold] &, Position[target, _Integer]][target]; lst //. Evaluate@pattlst :> Evaluate@target] 

Based on ubpdqn's answer, I wrote:

fun[u_, patt_] := Module[{p = Flatten@Position[Partition[u, Length[patt], 1], patt], rules, res}, rules = {x_, #} :> {Style[x, Red, Bold], #} & /@ Flatten[(Flatten@Position[patt, _Integer] - 1 + #) & /@ p]; res = MapIndexed[{#1, First@#2} &, u] /. rules; res[[;; , 1]]] colorfun[seq_, pat_] := Map[fun[#, pat] &, seq] 

Not playing well with BenchmarkPlot,I used my OEISSearch Package to generate the test data.

enter image description here enter image description here

So it seems that ubpdqn's function is faster.

$\endgroup$

3 Answers 3

1
$\begingroup$

Something different (but ugly):

fun[u_] := Module[{p = Flatten@Position[Partition[u, 3, 1], {1, _, 3}], rules, res}, rules = {x_, #} :> {Style[x, Red, Bold], #} & /@ Flatten[{#, # + 2} & /@ p]; res = MapIndexed[{#1, First@#2} &, u] /. rules; res[[;; , 1]] ] 

So,

test = {{1, 2, 3}, {1, 2, 3, 1, 2, 3, 4, 5}} fun/@test 

enter image description here

$\endgroup$
2
$\begingroup$

I'm lazy so this is short but not efficient in general case:

lst //. {x___, 1, y_, 3, z___} :> {x, Style[1, Red], y, Style[3, Red], z} 

enter image description here

$\endgroup$
2
  • $\begingroup$ and identical to my answer, which I gave a minute before. ;) $\endgroup$ Commented Apr 10, 2015 at 9:59
  • $\begingroup$ @Jinxed I'm sorry, you were 19sec late :) $\endgroup$ Commented Apr 10, 2015 at 10:02
2
$\begingroup$
lst//.{a___,1,s_,3,b___}:>{a,Style[1, Red],s,Style[3, Red],b} 
$\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.