5
$\begingroup$

Coloring elements of sublists has been dealt with in another question.

A solution for sublists was presented along the following lines.

Permutations[{1, 2, 3}] // 
MapAt[Style[#, Red] &, #, {1, #} & /@ Range[2, 2]] & // 
MapAt[Style[#, Blue] &, #, {2, #} & /@ Range[3, 3]] &    

This produces the output of a list of permutations {{1,2,3},{1,3,2}, {3,2,1}}, in which the first sublist {1,2,3} has the element 2 (in position 2) colored red and the second sublist {1,3,2} has the element 2 (in position 3) colored blue.

I would like to obtain the result where all sublists have the second element colored red and the third colored blue.

This should be produced regardless of the number of sublists in the list.

$\endgroup$

5 Answers 5

4
$\begingroup$

Call the coloring function for each sublist using /@.

(MapAt[Style[#, Blue] &, MapAt[Style[#, Red] &, #, 2], 3] &) /@ Permutations[{1, 2, 3}]

result

$\endgroup$
4
$\begingroup$

Using MapThread:

MapThread[Style[#1, #2] &, {#, {Black, Red, Blue}}] & /@ 
 Permutations[{1, 2, 3}]

enter image description here

$\endgroup$
4
$\begingroup$

Version 12 introduced SubsetMap which is a convenient generalization of MapAt:

SubsetMap[Thread[Style[#, {Red, Blue}]]&, #, {2, 3}]& /@ Permutations[{1, 2, 3}]

enter image description here

An alternative to SubsetMap and MapAt is to modify parts directly:

list = Permutations[{1, 2, 3}];
list[[All, {2, 3}]] = Thread[Style[#, {Red, Blue}]] & /@ list[[All, {2, 3}]];
list

same result

In versions 12.2+, we can also use ApplyTo:

f = Map[Thread@Style[#, {Red, Blue}] &];

list = Permutations[{1, 2, 3}];
list[[All, {2, 3}]] //= f;
list

enter image description here

$\endgroup$
3
$\begingroup$

Using SequenceReplace:

l = Permutations[Range[3]];
colors = {Black, Red, Blue};

Map[Style[#[[1]], #[[2]]] &, SequenceReplace[l, {x_} :> Transpose@{x, colors}],{2}]

Or using SequenceReplace and ReplaceAll:

SequenceReplace[l, {x_} :> Transpose@{x, colors}] /. {x_, y_} :> Style[x, y]

enter image description here

Edit:

Thanks, @Syed, for your kindly suggestion:

Transpose[{#, colors}] & /@ l /. {a_, b_} :> Style[a, b]
$\endgroup$
1
  • 1
    $\begingroup$ Simpler: Transpose[{#, colors}] & /@ l /. {a_, b_} :> Style[a, b] $\endgroup$
    – Syed
    Apr 16, 2023 at 14:59
1
$\begingroup$
a = Permutations[{1, 2, 3}];

c = {Black, Red, Blue};

Using ReplacePart

ReplacePart[a, {i_, j_} :> Style[a[[i, j]], c[[j]]]]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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