# Generate all possible codewords given a dictionary

**URL:** https://discourse.julialang.org/t/generate-all-possible-codewords-given-a-dictionary/81388
**Category:** General Usage
**Tags:** combinatorics
**Created:** [May 20, 2022, 5:33pm UTC](https://discourse.julialang.org/t/generate-all-possible-codewords-given-a-dictionary/81388 "2022-05-20T17:33:34Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![Alehud](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/alehud/32/125128_2.png) [@Alehud](https://discourse.julialang.org/u/Alehud)
#### Post date: [May 20, 2022, 5:33pm UTC](https://discourse.julialang.org/t/generate-all-possible-codewords-given-a-dictionary/81388/1 "2022-05-20T17:33:34Z")

</div>

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

```julia
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

```julia
['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.

```julia
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?

---

<div class="post-metadata">

### Author: ![Oscar\_Smith](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oscar_smith/32/25343_2.png) [@Oscar\_Smith](https://discourse.julialang.org/u/Oscar_Smith)
#### Post date: [May 20, 2022, 5:46pm UTC](https://discourse.julialang.org/t/generate-all-possible-codewords-given-a-dictionary/81388/2 "2022-05-20T17:46:25Z")

</div>

`Iterators.product(d,d)`

---

<div class="post-metadata">

### Author: ![Alehud](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/alehud/32/125128_2.png) [@Alehud](https://discourse.julialang.org/u/Alehud)
#### Post date: [May 20, 2022, 9:29pm UTC](https://discourse.julialang.org/t/generate-all-possible-codewords-given-a-dictionary/81388/3 "2022-05-20T21:29:27Z")

</div>

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

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

```
