Commit 1d63db8

mo khan <mo@mokhan.ca>
2022-04-06 15:53:13
complete the ransom note problem
1 parent d1fab1f
Changed files (1)
2022
04
2022/04/06/main.rb
@@ -0,0 +1,35 @@
+#!/usr/bin/env ruby
+
+=begin
+You're a criminal trying to write words using cutouts from a magazine.
+
+Return true or false given a magazine and a word to spell.
+
+magazine: [a,b,c,d,e,f]
+word: bed
+true
+
+=end
+
+def assert_equal(x, y)
+  raise "expected: #{x.inspect}, got: #{y.inspect}" unless x == y
+end
+
+class Solution
+  def self.valid?(magazine:, word:)
+    map = Hash.new { |h, k| h[k] = 0 }
+    magazine.each { |x| map[x] += 1 }
+
+    word.chars.each do |char|
+      val = map[char]
+      return false if val.nil? || val.zero?
+
+      map[char] -= 1
+    end
+    true
+  end
+end
+
+assert_equal(true, Solution.valid?(magazine: ['a', 'b', 'c', 'd', 'e', 'f'], word: 'bed'))
+assert_equal(false, Solution.valid?(magazine: ['a', 'b', 'c', 'd', 'e', 'f'], word: 'bat'))
+assert_equal(false, Solution.valid?(magazine: ['a', 'b', 'c', 'd', 'e', 'f'], word: 'beef'))