Skip to main content
3 of 4
Improved the explanation of the second part of the problem based on comments of the posters.
kurush
  • 45
  • 1
  • 6

Adding and subtracting from elements in a list

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.

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.

kurush
  • 45
  • 1
  • 6