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.
Meks (pronounced like tex-mex) is a graduate of Flatiron’s Full-Stack Engineer program. They are a software engineer primarily working Elixir, Phoenix LiveView, TailwindCSS, Postgres, and TypeScript.
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!
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)
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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.
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!
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)