Created
December 6, 2013 23:35
-
-
Save jojo89/7833998 to your computer and use it in GitHub Desktop.
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
dict = ["a", | |
"abdominal","a", "ace", "acre", "arc", "are", "area", "c", "car", "care", "ceca", "e", "ear", "era", "err", "r", "race", "racer", "rare", "re", "rear", "rec" | |
] | |
def jumble(source,dict) | |
matches = [] # => O(1) | |
source_hash = source.chars.inject(Hash.new(0)) { |h,v| h[v] += 1; h } | |
dict.each do |w| | |
word_hash = w.chars.inject(Hash.new(0)) { |h,v| h[v] += 1; h } | |
word_hash.each do |key, value| # => O(n) | |
word_hash[key]= word_hash[key] - source_hash[key]# => 0(1) | |
end | |
left_over = word_hash.select{|k,v| v >= 1} # => O(n) | |
if left_over == {} # => O(1) | |
matches << w # => O(1) | |
end | |
end | |
return matches | |
end | |
jumble("racecar", dict) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome work on this. So, I think you just wrote a little more code then you needed to, but you definitely nailed the concept. The point is that we don't care about the "order" of letters...only their "quantity." So now you can do something like:
Something along those lines, but yours actually works as well. Keeping track in a boolean is faster (O(1)) than line 15 above.
Make sense?