Skip to content

Instantly share code, notes, and snippets.

@broguinn
Created August 29, 2013 00:58
Show Gist options
  • Save broguinn/6373172 to your computer and use it in GitHub Desktop.
Save broguinn/6373172 to your computer and use it in GitHub Desktop.
anagrams
def anagrams(word, possible_anagrams)
unless possible_anagrams.is_a?(Array) || possible_anagrams.all? { |anagram| anagram.is_a?(String) }
raise TypeError.new("The possible anagrams must be an array")
end
possible_anagrams.find_all do |anagram|
word.chars.sort == anagram.chars.sort
end
end
require 'rspec'
require 'anagrams'
describe 'anagrams' do
it 'finds a simple match' do
anagrams("abc", ["cba"]).should eq ["cba"]
end
it 'finds all anagrams of a word from the list' do
anagrams("abc", ["cba", "bca", "abc", "ac", "adc"]).should eq ["cba", "bca", "abc"]
end
it 'raises an exception if it does not get a string' do
expect { anagram(2) }.to raise_exception
end
it 'raises an exception if it does not get an array of strings for the second arguement' do
expect { anagram("abc", [2, 3, 4]) }.to raise_exception
expect { anagram("abc", "abc") }.to raise_exception
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment