Created
August 31, 2012 04:03
-
-
Save xerxesb/3548956 to your computer and use it in GitHub Desktop.
How many ways can the letters in australia be arranged so that ONLY 2 A's are together?
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
# This generates all combinations of words with the letters in 'australia', | |
# and then filters down to include only words with two consequtive "a"s | |
# and then excludes any words with 3 consecutive "a"s, leaving the words with only 2 a's together. | |
# | |
# Answer: 30240 | |
class String | |
def each_char_with_index | |
0.upto(size - 1) do |index| | |
yield(self[index..index], index) | |
end | |
end | |
def remove_char_at(index) | |
return self[1..-1] if index == 0 | |
self[0..(index-1)] + self[(index+1)..-1] | |
end | |
end | |
@arr = Array.new | |
def permute(str, prefix = '') | |
if str.size == 0 | |
@arr << prefix | |
return | |
end | |
str.each_char_with_index do |char, index| | |
permute(str.remove_char_at(index), prefix + char) | |
end | |
end | |
permute("australia") | |
@arr.find_all{|t| t.include?("aa")}.reject{|t| t.include?("aaa")}.uniq.length |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment