Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.
a1 = {1, 2, 3, 4};
Do[a2 = DeleteCases[a1, x1];
  Do[a3 = DeleteCases[a2, x2];
   Do[a4 = DeleteCases[a3, x3];
    Do[Sow@{x1, x2, x3, x4};
     , {x4, a4}]
    , {x3, a3}]
   , {x2, a2}]
  , {x1, a1}] // Reap // Last

I would like replace my code with Nest, I have tried this

a1 = {1, 2, 3, 4};
Nest[Table[{i, j}, {i, a1}, {j, DeleteCases[#, i]}]~Flatten~1 &, a1, 3]

but it worked incorrect.

share|improve this question
8  
Why don't you use simply Permutations[{1, 2, 3, 4}] ??? –  Artes Oct 18 '13 at 18:09
1  
Like this : Select[Tuples[a1, 4], Length@Union@# == 4 &] –  Tangshutao Oct 19 '13 at 15:34
    
@Tangshutao Your method consume too much memory, also Select[Tuples[Range@4, 4], Unequal @@ # &] –  chyaong Oct 19 '13 at 17:39
    
@chyaong,+1,Thank you!Your method also takes less time. –  Tangshutao Oct 20 '13 at 4:25

2 Answers 2

up vote 7 down vote accepted

You can write something like this

a1 = {1, 2, 3, 4};
Nest[Flatten[Outer[Append, {#}, Complement[a1, #], 1] & /@ #, 2] &, Transpose@{a1}, 3]
{{1, 2, 3, 4}, {1, 2, 4, 3}, {1, 3, 2, 4}, {1, 3, 4, 2}, {1, 4, 2, 3}, 
 {1, 4, 3, 2}, {2, 1, 3, 4}, {2, 1, 4, 3}, {2, 3, 1, 4}, {2, 3, 4, 1}, 
 {2, 4, 1, 3}, {2, 4, 3, 1}, {3, 1, 2, 4}, {3, 1, 4, 2}, {3, 2, 1, 4}, 
 {3, 2, 4, 1}, {3, 4, 1, 2}, {3, 4, 2, 1}, {4, 1, 2, 3}, {4, 1, 3, 2}, 
 {4, 2, 1, 3}, {4, 2, 3, 1}, {4, 3, 1, 2}, {4, 3, 2, 1}}

However, as Artes pointed out it is the same as Permutations

 % == Permutations[a1]

True

share|improve this answer
a1 = {1, 2, 3, 4};
Nest[Table[{a}~Join~b, {a, a1}, {b, Select[#, FreeQ[#, a] &]}]~Flatten~1 &, {{}}, Length@a1]

{{1, 2, 3, 4}, {1, 2, 4, 3}, {1, 3, 2, 4}, {1, 3, 4, 2}, {1, 4, 2, 3}, {1, 4, 3, 2}, {2, 1, 3, 4}, {2, 1, 4, 3}, {2, 3, 1, 4}, {2, 3, 4, 1}, {2, 4, 1, 3}, {2, 4, 3, 1}, {3, 1, 2, 4}, {3, 1, 4, 2}, {3, 2, 1, 4}, {3, 2, 4, 1}, {3, 4, 1, 2}, {3, 4, 2, 1}, {4, 1, 2, 3}, {4, 1, 3, 2}, {4, 2, 1, 3}, {4, 2, 3, 1}, {4, 3, 1, 2}, {4, 3, 2, 1}}

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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