A little word play in Elixir

Another day, another exercise. This time it’s the oldie but goldie, anagram detection. For the innocent ones, taken from problem’s readme:

Write a program that, given a word and a list of possible anagrams, selects the correct sublist.
Given "listen" and a list of candidates like "enlists" "google" "inlets" "banana" the program should return a list containing "inlets".

And here’s one possible take on it:

defmodule Anagram do
  @doc """
  Returns all candidates that are anagrams of, but not equal to, 'base'.
  @spec match(String.t, [String.t]) :: [String.t]
  def match(base, candidates) do
    candidates |> Enum.filter(fn(candidate) ->
      !equal?(base, candidate) && anagram?(base, candidate)

  defp equal?(base, candidate) do
    String.downcase(base) == String.downcase(candidate)

  defp anagram?(base, candidate) do
    hash(base) == hash(candidate)

  defp hash(string) do
    string |> String.downcase |> String.split("") |> Enum.sort
Tagged , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: