4
$\begingroup$

Given some natural number $N$, I am interested in the set of all binary permutations of length $N$ (with the intention of storing in lists depending on how many $1$'s appear in each permutation). My code does the job but is not efficient as I am using nested For loops. Please advise on how you would adapt for more efficient evaluation.

My code (for $N=3$):

Num = 3; A = {};
For[q = 0,  q <= Num, q++, B = {}; 
 For[i = 1, i <= Num - 1, i++, If[i <= q, AppendTo[B, 0]]; 
  If[i >=   q, AppendTo[B, 1]]]; 
 If[Length[B] < Num, AppendTo[B, B[[1]]]]; 
 AppendTo[A, Pe = Permutations[B]] ]

A = Reverse[A]

{{{0, 0, 0}}, {{0, 0, 1}, {0, 1, 0}, {1, 0, 0}}, {{0, 1, 1}, {1, 0, 
   1}, {1, 1, 0}}, {{1, 1, 1}}}

Thanks for any assistance.

$\endgroup$
1
  • 2
    $\begingroup$ In[1353]:= perms[n_] := SortBy[Map[IntegerDigits[#, 2, n] &, Range[0, 2^n - 1]], Total] In[1354]:= perms[3] Out[1354]= {{0, 0, 0}, {0, 0, 1}, {0, 1, 0}, {1, 0, 0}, {0, 1, 1}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}} ?? $\endgroup$ Oct 18, 2021 at 15:00

1 Answer 1

5
$\begingroup$
GroupBy[Tuples[{0, 1}, 3], Total]
(*    <|0 -> {{0, 0, 0}},
        1 -> {{0, 0, 1}, {0, 1, 0}, {1, 0, 0}},
        2 -> {{0, 1, 1}, {1, 0, 1}, {1, 1, 0}},
        3 -> {{1, 1, 1}}|>                         *)

GatherBy[Tuples[{0, 1}, 3], Total]
(*    {{{0, 0, 0}},
       {{0, 0, 1}, {0, 1, 0}, {1, 0, 0}},
       {{0, 1, 1}, {1, 0, 1}, {1, 1, 0}},
       {{1, 1, 1}}}                          *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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