# Replacing one element of list

I have a list of sequences of x's and y's. I want to switch the last position to the "opposite" symbol - if x, replace with y; if y, replace with x.

It is in the following format:

{{{x,x,x,x,x,y,y},{x,x,x,x,y,y,x},{x,x,x,y,y,x,x},{x,x,y,y,x,x,x},
{x,y,y,x,x,x,x},{y,x,x,x,x,x,y},{y,y,x,x,x,x,x}},
{{x,x,x,x,y,x,y},{x,x,x,y,x,y,x},{x,x,y,x,y,x,x},{x,y,x,x,x,x,y},
{x,y,x,y,x,x,x},{y,x,x,x,x,y,x},{y,x,y,x,x,x,x}},
{{x,x,x,y,x,x,y},{x,x,y,x,x,x,y},{x,x,y,x,x,y,x},{x,y,x,x,x,y,x},
{x,y,x,x,y,x,x},{y,x,x,x,y,x,x},{y,x,x,y,x,x,x}}}


So for each monomial with length 7, I want to replace the last part with the opposite. Does anyone know an easy way to program it with Mathematica? I will be doing this for lists of different length: 7,11,13,15,17.

• @Kuba wicked :D Jun 11 '14 at 18:34
• @YvesKlett mine too, I've added A at the end to the result is clear now. Still not sure about my interpretation :)
– Kuba
Jun 11 '14 at 18:40
• @Kuba d´oh! Well, go on and answer, then! Jun 11 '14 at 18:40
• @Öskå splitting hairs ;-) Jun 11 '14 at 18:41

Let's say your matrix is A, this method does not depend of length of inner lists:

A[[All, All, -1]] = A[[All, All, -1]] /. {x -> y, y -> x};
A


This one doesn't even care about the depth of the array:

A /. a : {(x | y) ..} :> MapAt[# /. {x -> y, y -> x} &, a, {-1}]

• Yes, that works for my problem. Thank you very much! Jun 11 '14 at 18:49
• @Laura I'm glad it does. It is good habit to hold on with an accept a day or two, let's do not discourage others ;) you can still upvote it if you like. Good luck.
– Kuba
Jun 11 '14 at 18:51
• Kuba, I changed your ;; to All so that it will work in v7 too; I hope you don't mind. (It adds a character but it seems clearer too.) Why don't you include a pure MapAt solution using All (for v9)? Jun 11 '14 at 18:57
• Never mind the second part; I see kguler beat you to it. Jun 11 '14 at 18:57
• @Mr.Wizard I wasn't aware ;; does not work in V7. I guess I was writing Fors back in those days :P I will use All from now on, at least here.
– Kuba
Jun 11 '14 at 18:59

MapAt

dt = RandomChoice[{x, y}, {2, 3, 4}];
dt //TeXForm


$\left( \begin{array}{ccc} \{x,y,y,y\} & \{y,x,y,x\} & \{x,x,x,y\} \\ \{y,x,x,x\} & \{y,y,x,y\} & \{x,x,y,y\} \\ \end{array} \right)$

f1 = MapAt[# /. {x -> y, y -> x} &, #, {{All, All, -1}}] &;
f1 @ dt // TeXForm


$\left( \begin{array}{ccc} \{x,y,y,x\} & \{y,x,y,y\} & \{x,x,x,x\} \\ \{y,x,x,y\} & \{y,y,x,x\} & \{x,x,y,x\} \\ \end{array} \right)$

Replace

f2 = Replace[#, {a__, b : x | y} :> {a, b /. {x -> y, y -> x}}, Infinity] &;
f2 @ dt // TeXForm


$\left( \begin{array}{ccc} \{x,y,y,x\} & \{y,x,y,y\} & \{x,x,x,x\} \\ \{y,x,x,y\} & \{y,y,x,x\} & \{x,x,y,x\} \\ \end{array} \right)$