How to print alphabet in Elixir? (aa ab ac etc)

sweetness!

1 Like

Also, for comprehensions offer binary generators

``````iex(15)> alphabet = "abcdefghijklmnopqrstuvwxyz"
"abcdefghijklmnopqrstuvwxyz"
iex(16)> for <<x <- alphabet>>, do: <<"a", x>>
["aa", "ab", "ac", "ad", "ae", "af", "ag", "ah", "ai", "aj", "ak", "al", "am",
"an", "ao", "ap", "aq", "ar", "as", "at", "au", "av", "aw", "ax", "ay", "az"]
``````
8 Likes

for example here ` <<Enum.random(?A..?Z)>>` it works, but on my other example when I try to use <<>> it doesnt fix it

You should take these posts as hints what to look into, but maybe not start with binary generators just yet.

3 Likes

well yea hard coding the alphabet isnt a problem but imagine having a list of like 500 letters or something, hmm

Excel encodes the columns in the general pattern of what you need.

In Elixlsx you can find the utility function `encode_col` that implements the general case (see here):

``````  def encode_col(0), do: ""
def encode_col(num) when num <= 26, do: <<num + 64>>

def encode_col(num, suffix \\ "")
def encode_col(num, suffix) when num <= 26, do: <<num + 64>> <> suffix

def encode_col(num, suffix) do
mod = div(num, 26)
rem = rem(num, 26)

if rem == 0 do
encode_col(mod - 1, "Z" <> suffix)
else
encode_col(mod, <<rem + 64>> <> suffix)
end
end
``````

Your alphabet would start at `encode_col(27)`

Edit: you would need to lowercase the string (or adapt the code)

1 Like

TIL…

1 Like

`"a#{letter}"` != `"a#{[&1]}"`

In this case the `&1` is equivalent to `letter`, so that is not the meaningful difference. The difference is wrapping the `letter` in a list such that the compiler sees it as a charlist. Interpolating a charlist is different than interpolating an integer (which is what `letter` actually is when you pull it from a charlist).

1 Like