elixir

Calculate anagrams in Elixir

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once

For example:

  • "restful" = "fluster"
  • "funeral" = "real fun"
  • "adultery" = "true lady"
  • "customers" = "store scum"
  • "forty five" = "over fifty"

Create a new project using mix new anagram then let's write some test cases:

defmodule AnagramTest do
  use ExUnit.Case

  test "calculates anagram" do
    assert Anagram.anagram?("restful", "fluster") == true
    assert Anagram.anagram?("funeral", "realfun") == true
    assert Anagram.anagram?("adultery", "truelady") == true
    assert Anagram.anagram?("customers", "storescum") == true
    assert Anagram.anagram?("fortyfive", "overfifty") == true
    assert Anagram.anagram?("fiftyfive", "overfifty") == false
    assert Anagram.anagram?("funeral", "real fun") == false
  end
end


Now we have to write the code:

defmodule Anagram do
    def anagram?(a, b) do
    charlist(a) == charlist(b)
  end

  def charlist(w) do
    w |> String.trim() |> String.downcase() |> String.graphemes() |> Enum.sort()
  end
end


Run the tests mix test:

Compiling 1 file (.ex)
Generated anagram app
.

Finished in 0.1 seconds
1 test, 0 failures

Randomized with seed 752850


Done, now you have an anagram calculator!

Ali