Simpler way to create special binary Lists
This is faster:
ArrayFlatten[{{Tuples[{0, 1}, nn], Tuples[{1, 0}, nn]}}]
This is slower, but as an alternative approach:
IntegerDigits[Range[2^nn] (2^nn - 1), 2, 2 nn]
Update: Alternatives using ArrayPad
and PadRight
:
(out1 = ArrayPad[Tuples[{0, 1}, nn], {{0}, {0, nn}}, Tuples[{1, 0}, nn]]);
// AbsoluteTiming // First
0.344810
(out1a = PadRight[Tuples[{0, 1}, nn], {2^nn, 2 nn}, Tuples[{1, 0}, nn]]);
// AbsoluteTiming // First
0.315793
(out1b = ArrayReshape[Riffle[Tuples[{0, 1}, nn], Tuples[{1, 0}, nn]], {2^nn, 2*nn}]);
// AbsoluteTiming // First
0.687106
Simon's updated version is the fastest among the three methods:
(out1c = ArrayFlatten[{{Tuples[{0, 1}, nn], Tuples[{1, 0}, nn]}}]); //
AbsoluteTiming // First
0.259235
out1 == out1a == out1b == out1c
True
Original Post:
Join @@@ Transpose[{#, Reverse@#}] &@Tuples[{0, 1}, nn]
or
MapThread[Join, {#, Reverse@#} &@Tuples[{0, 1}, nn]]
{{0, 0, 0, 1, 1, 1}, {0, 0, 1, 1, 1, 0}, {0, 1, 0, 1, 0, 1}, {0, 1, 1, 1, 0, 0}, {1, 0, 0, 0, 1, 1},
{1, 0, 1, 0, 1, 0}, {1, 1, 0, 0, 0, 1}, {1, 1, 1, 0, 0, 0}}
Note: both of these are much slower than OP's method.
ArrayReshape[Transpose@{#, Reverse@#} &@Tuples[{0, 1}, nn], {2^nn, 2*nn}]
is much faster but still not as fast as OP's approach.
Starting with a fresh kernel to keep caching from affecting the timings
f1[nn_] := f1[nn] =
ArrayReshape[
Riffle[Tuples[{0, 1}, nn], Tuples[{1, 0}, nn]],
{2^nn, 2*nn}]
f2[nn_] := f2[nn] =
Flatten /@ Transpose[{Tuples[{0, 1}, nn], Tuples[{1, 0}, nn]}]
Adding solution provided by @SimonWoods
f3[nn_] := f3[nn] =
ArrayFlatten[{{Tuples[{0, 1}, nn], Tuples[{1, 0}, nn]}}]
Since the time grows exponentially, use ListLogPlot
ListLogPlot[
Table[{
AbsoluteTiming[f1[n]][[1]],
AbsoluteTiming[f2[n]][[1]],
AbsoluteTiming[f3[n]][[1]]}, {n, 24}] //
Transpose,
Joined -> True,
PlotLegends -> {f1, f2, f3}]
Solution provided by @SimonWoods performs best. Verifying that the functions are equivalent
And @@ Table[f1[n] === f2[n] === f3[n], {n, 24}]
(* True *)