Search code examples
juliaiterationbinary-string

IterTools product in Julia


I would like to produce lists of 0 and 1 in Julia using IterTools. For example, in Python I can do:

for bits in itertools.product([0, 1], repeat=5):
    print(bits)

This will produce

(0, 0, 0, 0, 0)
(0, 0, 0, 0, 1)
(0, 0, 0, 1, 0)
(0, 0, 0, 1, 1)
(0, 0, 1, 0, 0)
(0, 0, 1, 0, 1)
(0, 0, 1, 1, 0)
...

I learned that in Julia there is similar functionality. Using IterTools, I can do:

for bits in product([0,1], [0,1])
    @show  bits
end

This will produce

(0,0)
(0,1)
...

The problem is that I need to hardcode the number of factors. For example, if I want bitstrings of length 5, I need to call product([0,1],[0,1],[0,1],[0,1],[0,1]).

I would like to know how to get arbitrary length lists using something similar to Python's repeat argument.


Solution

  • You can simply use the Iterators.repeated function to get a similar output to the Python function. You can set the n = 5 or any other value to get lists of arbitrary lengths.

    julia> for bits in Iterators.product(Iterators.repeated((0, 1), 5)...)
               println(bits)
           end
    (0, 0, 0, 0, 0)
    (1, 0, 0, 0, 0)
    (0, 1, 0, 0, 0)
    (1, 1, 0, 0, 0)
    (0, 0, 1, 0, 0)
    (1, 0, 1, 0, 0)
    ...