I don't know if there is a built-in function for this, but I'm thinking about something like this
Outer[List, Table[{0,1},{n}] ]
But Outer
doesn't accept this type of input. What should I do?
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityTuples
is surely better but you can make Outer
work very simply too:
Outer[List, ##] & @@ Table[{0, 1}, {3}]
{{{{0, 0, 0}, {0, 0, 1}}, {{0, 1, 0}, {0, 1, 1}}}, {{{1, 0, 0}, {1, 0, 1}}, {{1, 1, 0}, {1, 1, 1}}}}
Also applicable is Array
:
Array[List, {2, 2, 2}, 0]
{{{{0, 0, 0}, {0, 0, 1}}, {{0, 1, 0}, {0, 1, 1}}}, {{{1, 0, 0}, {1, 0, 1}}, {{1, 1, 0}, {1, 1, 1}}}}
Complete with flattening:
n = 4;
{Array[List, ConstantArray[2, n], 0, ## &]}
{{0, 0, 0, 0}, {0, 0, 0, 1}, {0, 0, 1, 0}, {0, 0, 1, 1}, {0, 1, 0, 0}, {0, 1, 0, 1}, {0, 1, 1, 0}, {0, 1, 1, 1}, {1, 0, 0, 0}, {1, 0, 0, 1}, {1, 0, 1, 0}, {1, 0, 1, 1}, {1, 1, 0, 0}, {1, 1, 0, 1}, {1, 1, 1, 0}, {1, 1, 1, 1}}
You could try Tuples
:
Tuples[{0, 1}, 4]
(*
{{0,0,0,0},{0,0,0,1},{0,0,1,0},{0,0,1,1},
{0,1,0,0},{0,1,0,1},{0,1,1,0},{0,1,1,1},
{1,0,0,0},{1,0,0,1},{1,0,1,0},{1,0,1,1},
{1,1,0,0},{1,1,0,1},{1,1,1,0},{1,1,1,1}}
*)
While Tuples
works well for generating all of them at once, sometimes we need to enumerate them one by one, without keeping all previous results in memory. In this case you can use
Do[ ... IntegerDigits[k, 2, n] ..., {k, 0, 2^n-1}]
...
do? I get a syntax error when I execute it.
$\endgroup$
Jan 14, 2015 at 19:47
Do
loop.
$\endgroup$
. . .
for that purpose to reduce confusion with RepeatedNull
; I'm not sure if it works.
$\endgroup$
Jan 14, 2015 at 22:01
IntegerDigits[Range[2^5], 2, 5]
or as a function:
myList[n_: Integer] := Flatten[Array[List, Table[2, {n}], 0], n - 1]
But if you need to display the digits as a string rather than a comma-separated list:
StringJoin /@ Tuples[{"0", "1"}, 5]
What is your specific need for such sequences? That will help us help you.
IntegerString
: With[{n = 8}, IntegerString[#, 2, n] & /@ Range[2^n - 1]]
. It's twice as fast.
$\endgroup$
Jan 14, 2015 at 20:42
Distribute[ConstantArray[{0, 1}, 4], List] // TeXForm
$ \left( \begin{array}{cccc} 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 1 & 1 \\ 0 & 1 & 0 & 0 \\ 0 & 1 & 0 & 1 \\ 0 & 1 & 1 & 0 \\ 0 & 1 & 1 & 1 \\ 1 & 0 & 0 & 0 \\ 1 & 0 & 0 & 1 \\ 1 & 0 & 1 & 0 \\ 1 & 0 & 1 & 1 \\ 1 & 1 & 0 & 0 \\ 1 & 1 & 0 & 1 \\ 1 & 1 & 1 & 0 \\ 1 & 1 & 1 & 1 \\ \end{array} \right)$