Created
August 29, 2013 00:58
-
-
Save broguinn/6373172 to your computer and use it in GitHub Desktop.
anagrams
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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