Created
August 29, 2013 16:22
-
-
Save dustinbrownman/6380278 to your computer and use it in GitHub Desktop.
Expects a word and an array of possible anagrams of that word. Returns an array of all true anagrams.
This file contains hidden or 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 hidden or 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