master
1#!/usr/bin/env ruby
2
3=begin
4You're a criminal trying to write words using cutouts from a magazine.
5
6Return true or false given a magazine and a word to spell.
7
8magazine: [a,b,c,d,e,f]
9word: bed
10true
11
12=end
13
14def assert_equal(x, y)
15 raise "expected: #{x.inspect}, got: #{y.inspect}" unless x == y
16end
17
18class Solution
19 def self.valid?(magazine:, word:)
20 map = Hash.new { |h, k| h[k] = 0 }
21 magazine.each { |x| map[x] += 1 }
22
23 word.chars.each do |char|
24 val = map[char]
25 return false if val.nil? || val.zero?
26
27 map[char] -= 1
28 end
29 true
30 end
31end
32
33assert_equal(true, Solution.valid?(magazine: ['a', 'b', 'c', 'd', 'e', 'f'], word: 'bed'))
34assert_equal(false, Solution.valid?(magazine: ['a', 'b', 'c', 'd', 'e', 'f'], word: 'bat'))
35assert_equal(false, Solution.valid?(magazine: ['a', 'b', 'c', 'd', 'e', 'f'], word: 'beef'))