16 Jul 2013, 02:25

Dave Thomas (338 posts)

  • Write anagram?(word1, word2) that returns true if its parameters are anagrams.
A Possible Solution
defmodule MyString do

  def anagram(sqs1, sqs2), do: Enum.sort(sqs1) == Enum.sort(sqs2)


IO.inspect MyString.anagram('cat', 'act')                    #=> true
IO.inspect MyString.anagram('cat', 'actor')                  #=> false
IO.inspect MyString.anagram('incorporates', 'procreations')  #=> true

22 Dec 2013, 17:44

Chris Doggett (3 posts)

Here’s what I came up with, not using any built-in libraries. If the two words are anagrams, then adding all the characters in word1 as ints, and subtracting all the characters in word2 should leave you with 0.

defmodule Parse do
  def anagram?(word1, word2) do
    _anagram?(word1, word2, 0) == 0

  defp _anagram?([], [], acc), do: acc
  defp _anagram?([h|_], [], acc), do: acc + h
  defp _anagram?([], [h|_], acc), do: acc - h
  defp _anagram?([h1|t1], [h2|t2], acc) do
    _anagram?(t1, t2, acc + h1 - h2)

EDIT: Actually, after thinking about it some more, this won’t work, as it will consider ‘cat’ and ‘bbt’ to be anagrams.

29 Apr 2014, 15:27

Ernie Miller (4 posts)

An alternative I ended up with was to use list subtraction:

def anagram?(word1, word2) do
  (word1 -- word2) == '' and
    (word2 -- word1) == ''
  You must be logged in to comment