Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def validate(program)
- count = 0
- program.each do |instruction|
- case instruction
- when :push
- count += 1
- when :reduce
- return false if count < 2
- count -= 1
- end
- end
- return true
- end
- def execute(program, nums, operators)
- stack = []
- log = []
- nums = nums.dup
- operators = operators.dup
- program.each do |instruction|
- case instruction
- when :push
- a = nums.pop
- stack.push Rational(a)
- log << "push #{a}"
- when :reduce
- a = stack.pop
- b = stack.pop
- operator = operators.pop
- stack.push a.send(operator, b)
- log << "reduce with #{operator}"
- end
- end
- return stack.last, log
- end
- def log2expr(log)
- stack = []
- log.each do |i|
- case i
- when /^push (.+)/
- stack.push $1
- when /^reduce with (.+)/
- a = stack.pop
- b = stack.pop
- stack.push "(#{a} #{$1} #{b})"
- end
- end
- stack.last
- end
- if ARGV.size < 2
- puts "Usage: ruby1.9.1 #{__FILE__} <target> <num1> [<num2> <num3> ...]"
- exit
- end
- NUMS = ARGV[1..-1].map(&:to_i)
- ([:push] * NUMS.size + [:reduce] * (NUMS.size - 1)).permutation do |program|
- next unless validate(program)
- NUMS.permutation do |nums|
- [:+, :-, :*, :/].repeated_permutation(NUMS.size - 1) do |operators|
- begin
- result, log = execute(program, nums, operators)
- if result == ARGV[0].to_i
- puts log
- puts ""
- puts "=> #{log2expr(log)}"
- exit
- end
- rescue ZeroDivisionError
- end
- end
- end
- end
- puts "No Answer"
Add Comment
Please, Sign In to add comment