diff options
Diffstat (limited to '2022/04/06/main.rb')
| -rw-r--r-- | 2022/04/06/main.rb | 35 |
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')) |
