DEV Community

Discussion on: Sort a String using a Custom Alphabet in Elixir

lindentree profile image
Linden Chiu

Thanks for the educational article!

I had a question about your compare_alpha function; I think it's possible to map the alphabet to its indices? That way you can look up the index of any letter in the map in close to constant time, rather than iterating over a list with Enum.find_index. I rewrote your module with that implementation, and compared both versions with the benchee library, it seems to run faster with the modification.

mmcclure11 profile image
Meks (they/them) Author

Oh, I hadn't considered that! That's a really interesting take on it. Would you mind sharing the code for how you wrote compare_alpha? I'd love to test it out too and I can update the post with the new insight!

lindentree profile image
Linden Chiu • Edited

map = alphabet
|> String.split("", trim: true)
|> Enum.with_index()
|> Enum.reduce(%{}, fn({k,v}, acc)-> Map.put(acc, k, v) end)

You can create this map in the main alphabetize function, so you only have to do it once.
Then you can pass it into compare_alpha(a, b, map), and it becomes just:

map[a] < map[b]

I used a regular string for the alphabet instead of a sigil; I'm not familiar with Elixir, so I didn't know how to pass the indices from the list into the reduce function. (EDIT: Enum.with_index() works on the sigil, so you don't need to split an alphabet string)