Skip to content

Instantly share code, notes, and snippets.

@jojo89
Created December 6, 2013 23:35
Show Gist options
  • Save jojo89/7833998 to your computer and use it in GitHub Desktop.
Save jojo89/7833998 to your computer and use it in GitHub Desktop.
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)
@ryanwjackson
Copy link

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:

is_possible = true
word_hash.each do |key,val|
  is_possible = false and break unless source_hash.has_key?(key) && source_hash[key] >= val
end
matches << w if is_possible

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment