3
$\begingroup$

I need a defined function f[n_] satisfying

f[2]==Flatten[Table[{i, j}, {i, 1, 2}, {j, 1, 2}], 1]
f[3]==Flatten[Table[{i, j, k}, {i, 1, 2}, {j, 1, 2}, {k, 1, 2}], 2]
f[4]==Flatten[Table[{i, j, k, l}, {i, 1, 2}, {j, 1, 2}, {k, 1, 2}, {l, 1, 2}], 3]
.
.
.
etc.
$\endgroup$
0

4 Answers 4

8
$\begingroup$

You can just use Tuples:

f[n_] := Tuples[{1, 2}, n];

Then:

f[2]
{{1, 1}, {1, 2}, {2, 1}, {2, 2}}
$\endgroup$
4
$\begingroup$

The Shadowray's answer is the right one, but just for the sake of answering directly to the question of how to build a function using exactly the commands listed in the OP:

f[n_Integer, imin_Integer, imax_Integer] /; (n > 0 && imin > 0 && imax > 0) := 
 Flatten[ReleaseHold@
   Block[{vars = Table[Unique[], n]}, 
    Hold[Table][#, Sequence @@ ({#, imin, imax} & /@ #)] & @ vars], 
   n - 1]
$\endgroup$
3
$\begingroup$

Just for something different:

f[n_] := IntegerDigits[Range[0, 2^n - 1], 2, n] + 1
$\endgroup$
1
$\begingroup$

My go at this problem, as Stitch one, would be:

f[n_Integer /; n >= 1] := Flatten[Table[{##1}[[All, 1]], ##1] & @@
  Table[{Unique@"i", 1, 2}, n], n - 1]

Which is more easily generalizable.

$\endgroup$

Your Answer

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

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