3
$\begingroup$

I am new to Mathematica, this forum and programming in general.

I m trying to fulfill a given task. I want to write a function, which takes as input an positive integer, say $n$, and returns a table of all possible bit strings of length $n$. So, for example, f[3] should return

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

If anyone could help me I'd be grateful.

$\endgroup$
1
  • $\begingroup$ Somehow it cut of the beginning of my post. There is a "Hello together" missing :D $\endgroup$ – Jolle Dec 31 '19 at 16:28
5
$\begingroup$

Take a look to Tuples, more specifically, try for example Tuples[{0, 1}, 4].

$\endgroup$
1
  • $\begingroup$ Ja thank you very much. This solves my problem. $\endgroup$ – Jolle Dec 31 '19 at 16:54
4
$\begingroup$

You say your goal is to write a function to carry out the task you describe. Then you should consider constraining the function argument to be a positive integer. Like so,

bits[n_Integer?Positive] := Tuples[{0, 1}, n]

Then

bits[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}}

but

bits[-3]

will not evaluate, and neither will

bits[3.]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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