Skip to content

Instantly share code, notes, and snippets.

@dflima
Last active December 5, 2018 15:32
Show Gist options
  • Save dflima/2ac1382bc778917be82020bd3248a084 to your computer and use it in GitHub Desktop.
Save dflima/2ac1382bc778917be82020bd3248a084 to your computer and use it in GitHub Desktop.
That’s all the Elixir code you need to find an anagram of a word.
defmodule Anagram do
@moduledoc """
iex(1) > Anagram.match("dog", ["apple", "cow", "god"])
["god"]
"""
@spec match(String.t(), list()) :: list()
def match(base, candidates) when is_list(candidates) do
base_fingerprint = fingerprint(base)
candidates
|> Enum.filter(&(fingerprint(&1) == base_fingerprint))
end
@spec fingerprint(String.t()) :: list()
defp fingerprint(string) do
string
|> String.downcase()
|> String.to_charlist()
|> Enum.sort()
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment