# Rearrange the list with some rules

I am trying to solve physic problem on operators which are not commute. However, I am not good at coding, so I am having some problem with Mathematica code.

Let's define my list such that

b a a a


The rules are that b and a are commute, same elements are commute(a and a), but a and a or b and b are not commute.

a a = a a + 1
b b = b b + 1


My goal is place b at the end, and place element with  at the end.

baaa -> b (aa + 1) a -> baaa + ba
-> ba (aa + 1) + ba -> baaa + 2 ba
-> aaab + 2 ab


I thought it might be good for me to use list-manipulation.

{b, a, a, a } ->  { a, a, a, b } + 2 { a , b }


Similarly

{b, b, a, a} -> { a, a, b, b } +{a a}

{b, b, b, a} -> { a, b, b, b } + 2 {a b}

{a, a, a, a} -> { a, a, a, a} +3 {a,a}

{a, a, a, a} -> { a, a, a, a} +2 {a,a} +2 {a+a}
->{ a, a, a, a} + 4{a+a} + 2


Anyone can suggest me what command shall I use? I think I can use If[], MemberQ[] and Select[]. However, I am not sure where to start.

Thank you

• For me your example is a bit too cryptic. Can't you come up with a more simple/clear example? – Kay Apr 14 '16 at 15:31
• You should look up NonCommutativeMultiply and the many questions about boson algebra on this site. For instance, this one and this one. – march Apr 14 '16 at 15:52
• Start with this example rule = {{h___, b[n_], a[m_], t___} -> {h, a[m], b[n], t}, {h___, a[n_], a[m_], t___} /; n < m -> {h, a[m], a[n], 1, t}, {h___, b[n_], b[m_], t___} /; n < m -> {h, b[m], b[n], 1, t}, {h___, 1, a[n_], t___} -> {h, a[n], 1, t}, {h___, 1, b[n_], t___} -> {h, b[n], 1, t}}; {b, a, a, a} //. rule and study this to understand it. Try this on various lists. Then edit your post to show how you used this and examples where more rules are needed. – Bill Apr 14 '16 at 16:01
• Thank you @bill for the generous guide! – Saesun Kim Apr 14 '16 at 20:55

You could use NonCommutativeMultiply. For instance:

Unprotect[NonCommutativeMultiply];

o_ ** 1 := o;
1 ** o_ := o;

o_ ** p_Plus := Plus @@ (o ** # & /@ p);
p_Plus ** o_ := Plus @@ (# ** o & /@ p);

o1_ ** Times[k : Except[_a | _b], o2_] := k o1 ** o2;
Times[k : Except[_a | _b], o1_] ** o2_ := k o1 ** o2;

o1_b ** o2_a := o2 ** o1;

MakeBoxes[NonCommutativeMultiply[e1_, e2_], StandardForm] :=
RowBox[{MakeBoxes[e1, StandardForm], MakeBoxes[e2, StandardForm]}];

Protect[NonCommutativeMultiply];

a /: a ** a := a ** a + 1;
b /: b ** b := b ** b + 1;


b ** a ** a ** a
(* 2 (a b) + a a a b *)

b ** b ** a ** a
(* a a + a a b b *)

b ** b ** b ** a
(* 2 (a b) + a b b b *)

a ** a ** a ** a
(* 3 (a a) + a a a a *)

a ** a ** a ** a
% // Expand
(* 2 (a a) + 2 (1 + a a) + a a a a *)
(* 2 + 4 (a a) + a a a a *)

• @SaesunKim Thanks for the accept! :-) – user31159 Apr 14 '16 at 21:51