# Binary permutation list code in Mathematica

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.

• 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}} ?? Commented Oct 18, 2021 at 15:00

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}}}                          *)