16 Jul 2013, 02:25
Dave_gnome_head_isolated_pragsmall

Dave Thomas (337 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)

end

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
Generic-user-small

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
  end

  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)
  end
end

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
Ernie2_pragsmall

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) == ''
end
  You must be logged in to comment