Generate all possible codewords given a dictionary

I have a 1D array that is my “dictionary”. E.g.,

d = ['a', 'b', 'c']

I want to generate all possible codewords of length n composed of elements from d. For example, if n = 2, then the output I expect is

['a', 'a']
['a', 'b']
['a', 'c']
['b', 'a']
['b', 'b']
['b', 'c']
['c', 'a']
['c', 'b']
['c', 'c']

I’ve come up with the following code for this.

d = ['a', 'b', 'c']
n = 2
codeword = fill(' ', n)
for i in 0:length(d)^n - 1
    for k in 0:n-1
        codeword[k+1] = d[(i÷(length(d)^k))%length(d) + 1]
    end
    println(codeword)
end

Is there a more elegant way to do this? Or perhaps there exists a function in any of the packages that could do this?

Iterators.product(d,d)

3 Likes

Thanks! To completely answer my question, here is the generalization to arbitrary n.

d = ['a', 'b', 'c']
n = 4
dd = fill(d, n)
for c in IterTools.product(dd...)
    println(c)
end