Created
October 10, 2011 01:46
-
-
Save marcelmorgan/1274462 to your computer and use it in GitHub Desktop.
Trying all permutations of a word against a dictionary
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 try_all_permutations(word, dictionary, pos) | |
if word[pos].nil? | |
raise "Position #{pos} not in word list" | |
elsif pos == (word.length - 1) | |
puts word if dictionary.member? word | |
else | |
try_all_permutations(word, dictionary, pos+1) | |
for i in ((pos+1)..(word.length-1)) | |
word[i], word[pos] = word[pos], word[i] | |
try_all_permutations(word, dictionary, pos+1) | |
word[i], word[pos] = word[pos], word[i] | |
end | |
end | |
end | |
try_all_permutations "tac", %w{cat act}, 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment