Created
April 4, 2014 22:03
-
-
Save Streek/9983954 to your computer and use it in GitHub Desktop.
Solve for Anagram
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
#Keith Connolly | |
#require ruby -v 1.9.2 or higher. | |
#Extend String because it's clean. | |
class String | |
#does the same as permutation but on a string. | |
def char_arr(&block) | |
#Split all chars into an array. | |
arr = split(//) | |
#Pick all possible arrangements of that array. | |
arr.permutation { |i| yield i.join } | |
end | |
end | |
#Setup a few vars for display | |
#Our subject words... | |
words = %w("parts flights trips pears fights parse apple spear spears smear spares") | |
hits = [] | |
int = 0 | |
#The needle calls char_arr, then checks if that permutation appears in each word. | |
"spare".char_arr do |word| | |
#simple loop counter for output. | |
int=int+1 | |
#If a hit is found add to array for display. | |
hits << word if words.include?(word) | |
end | |
#This is not the most efficient way of doing this but I find it quick enough and elegant. | |
#I would refine for a production environment. | |
puts "Loops Required for Results: #{int.to_s}" #Display loop count. | |
puts "Hits: #{hits.to_s}" #Display which words match. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment