Google Code Jam is here again!
A great opportunity to practice with the excellent exercises provided. I just took exercise A from the Qualification Round 2009.
If you have a quick look at it… aren’t they asking for pattern matching? Aren’t you seeing regular expressions there? I did, they were just using “( )” instead of “[ ]“. So… why re-implement an algorithm that is already available and efficiently programmed at almost every standard library? Translate into a legal regular expression and let the library work for you.
Here is a possible solution to the problem. It lets you play again with lots of Ruby stuff and passes Google’s tests. Great for learning the language!
f = File.open(ARGV[0])
l, d, n = f.gets.split
alien_words = Array.new
for alien_word in 1..d.to_i
alien_words.push f.gets.chomp
end
for j in 1..n.to_i
pattern = f.gets.chomp
pattern = pattern.gsub("(","[")
pattern = pattern.gsub(")","]")
test_case = Regexp.new pattern
matches = 0
alien_words.each do |word|
unless(result = word.match(test_case)).nil?
matches = matches + 1
end
end
puts "Case ##{j}: #{matches}"
end
Input Files: Example in the exercise, Small file, Large file
Output Files (generated by the program above): Example in the exercise, Small file, Large file