Skip to content

Instantly share code, notes, and snippets.

@hamadu
Created September 12, 2018 03:43
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save hamadu/ac8a17f311121a0cd3679591660be76a to your computer and use it in GitHub Desktop.
combo_grader.rb
# problem statement: https://ioi2018.jp/wp-content/tasks/contest1/combo.pdf
# usage: ruby combo_grader.rb "your program"
class ComboGrader
KEYS = %w[A B X Y].freeze
COMMAND_LENGTH = 100
QUERY_LENGTH_LIMIT = COMMAND_LENGTH * 4
QUERY_LIMIT = 103
def run(program)
@program = IO.popen(program, mode = "r+")
mystery_command = generate(COMMAND_LENGTH)
QUERY_LIMIT.times do
type, contents = fetch_and_parse_query
if type == '!'
query_answer(mystery_command, contents)
else
@program.puts query_ask(mystery_command, contents)
end
end
print_and_exit(['Query limit exceeded'])
end
private
def print_and_exit(messages = [], success = false)
STDERR.puts messages.join("\n")
@program.close
exit(success ? 0 : 1)
end
def query_answer(mystery_command, query)
if mystery_command == query
print_and_exit(['Congratulations!', "Command was #{query} as you answered."], true)
else
print_and_exit(['Wrong answer.', "Command was #{mystery_command} but you answered #{query}."])
end
end
def query_ask(mystery_command, query)
if query.length > QUERY_LENGTH_LIMIT
print_and_exit(['Query too long.', "Your query #{query} is too long: over #{QUERY_LENGTH_LIMIT} characters."])
end
1.upto(mystery_command.length).each do |prefix_length|
prefix = mystery_command.slice(0, prefix_length)
unless query.include?(prefix)
return prefix_length-1
end
end
mystery_command.length
end
def fetch_and_parse_query
query_type, contents = @program.gets.chomp.split(' ')
print_and_exit(['invalid query']) unless %w[? !].include?(query_type)
[query_type, contents]
end
def generate(length)
first_key = KEYS.sample
sequence_keys = KEYS - [first_key]
first_key + Array.new(length-1).map { sequence_keys.sample }.join
end
end
ComboGrader.new.run(ARGV.first)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment