summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authormo khan <mo@mokhan.ca>2022-04-06 09:53:13 -0600
committermo khan <mo@mokhan.ca>2022-04-06 09:53:13 -0600
commit1d63db81ca534e0b089dc0f1467ef1a80863538c (patch)
treea9d32034359dd575ef7bd1d710719552a25005cf
parentd1fab1fde1ccaf4f991eb705ad0722886aa21f67 (diff)
complete the ransom note problem
-rw-r--r--2022/04/06/main.rb35
1 files changed, 35 insertions, 0 deletions
diff --git a/2022/04/06/main.rb b/2022/04/06/main.rb
new file mode 100644
index 0000000..9233e13
--- /dev/null
+++ b/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'))