Skip to content

Instantly share code, notes, and snippets.

@dcoxall
Created May 8, 2011 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcoxall/961644 to your computer and use it in GitHub Desktop.
Save dcoxall/961644 to your computer and use it in GitHub Desktop.
My Google Code Jam Letter Stamper Solution
# Extend the Array class to provide a
# contains? method and a method
class Array
def contains?(item)
return false if self.nil?
self.each do |i|
return true if (item == i)
end
return false
end
# Calculates the number of required stack operations
# that fit in with Googles criteria
def calc_actions
actions = 0
stack = Array.new
self.each do |g|
if (stack.last != g)
if (stack.contains? g)
until(stack.last == g) do
stack.pop
actions += 1
end
else
stack.push g
actions += 1
end
end
actions += 1 # Stamp the last item on stack
end
until (stack.last.nil?) do
stack.pop
actions += 1
end
return actions
end
end
# Extend the string class to make a conveniance
# method to turn a string into a grade array
class String
def to_grades()
return self.scan /A|B|C/
end
end
# Get the number of tests
t_count = gets.chomp.to_i
ct_count = 1
output = []
# Generate output
until (ct_count > t_count) do
grades = gets.chomp.upcase.to_grades
output << "Case \##{ct_count}: #{grades.calc_actions().to_s}"
ct_count += 1
end
# Output
output.each { |o| puts o }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment