Skip to content

Instantly share code, notes, and snippets.

@burtlo
Last active December 16, 2015 14:59
Show Gist options
  • Save burtlo/5452901 to your computer and use it in GitHub Desktop.
Save burtlo/5452901 to your computer and use it in GitHub Desktop.
class String
def char_counts_hash
char_hash = Hash.new(0)
each_char {|char| char_hash[char] += 1 }
char_hash
end
def anagram_of?(word)
word.char_counts_hash == char_counts_hash
end
end
class Anagram
def initialize(word)
@word = word
end
attr_reader :word
def match(words)
words.find_all {|anagram| word.anagram_of?(anagram) }
end
end
require 'minitest/autorun'
require 'minitest/pride'
require_relative './anagram'
class AnagramTest < MiniTest::Unit::TestCase
def test_no_matches
detector = Anagram.new('diaper')
assert_equal [], detector.match(%w(hello world zombies pants))
end
def test_detect_simple_anagram
detector = Anagram.new('ba')
anagrams = detector.match(['ab', 'abc', 'bac'])
assert_equal ['ab'], anagrams
end
def test_detect_anagram
detector = Anagram.new('listen')
anagrams = detector.match %w(enlists google inlets banana)
assert_equal ['inlets'], anagrams
end
def test_multiple_anagrams
detector = Anagram.new('allergy')
anagrams = detector.match %w(gallery ballerina regally clergy largely leading)
assert_equal ['gallery', 'regally', 'largely'], anagrams
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment