Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
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 &] – Shutao TANG 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. – Shutao TANG Oct 20 '13 at 4:25
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.