I'm trying to solve an aparently simple problem.
Given a list of length n
, {a1,b1,c1,d1...}
I want to perform two simple operations, and form a new list from each one: {a1+1,b1-1,c1,d1...}
, {a1,b1+1,c1-1,d1...}
, {a1,b1,c1+1,d1-1...}
and so on, and {a1-1,b1+1,c1,d1...}
and so on.
The list elements must not be greater or less than certain values after the addition or substraction. In {a1+1,b1-1,c1,d1...}
, {a1,b1+1,c1-1,d1...}
, {a1,b1,c1+1,d1-1...}
each element must be constrained: a1<max
and b1>0
, b1<max
and c1>0
, etc.
Using this lists I finally use the original list and the n
new lists to get a list of the form: {Join[list,new1],Join[list,new2],...}
To solve this problem I wrote a code that although works, takes a very long time to calculate for several sets of list {{a1,b1,c1,d1...}, {a2,b2,c2,d2...}...}
. Here I post an example using only a list with two sublists, with four elements each one: {{1, 2, 0, 2}, {2, 2, 1, 1}}
lst1 = {{1, 2, 0, 2}, {2, 2, 1, 1}};
dim = Partition[Range[Length@First@lst1], 2, 1];
list = li[]; (*to save the "composed" lists*)
(lst = #;
lst2 = Partition[lst, 2, 1];
lst31 = MapThread[If[#1 < 2 && #2 > 0, {#1 + 1, #2 - 1}, {#1, #2}] &,Transpose@lst2];
lst41 = Union@MapThread[ReplacePart[lst, {#1[[1]]-> #2[[1]], #1[[2]]-> #2[[2]]}]&, {dim,lst31}];
lst32 = MapThread[If[#1 > 0 && #2 < 2, {#1 - 1, #2 + 1}, {#1, #2}]&,Transpose@lst2];
lst42 = Union@MapThread[ReplacePart[lst, {#1[[1]]-> #2[[1]], #1[[2]]-> #2[[2]]}]&, {dim, lst32}];
lst61 = Join[lst, #] & /@ lst41;
lst62 = Join[lst, #] & /@ lst42;
lst6 = Union@Join[lst61, lst62];
list = li[list, lst6];
) & /@ lst1;
list = List @@ Flatten@list
Any advice to improve the performance of the code would be greatly appreciated!
Edit
Based on comments, I tried to explain better the second part of my problem giving a numerical example.
Edit 2
I have added a more precise description about the constraints of the elements of the lists.