Guest User

Untitled

a guest
Oct 17th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.76 KB | None | 0 0
  1. def validate(program)
  2.     count = 0
  3.     program.each do |instruction|
  4.         case instruction
  5.         when :push
  6.             count += 1
  7.         when :reduce
  8.             return false if count < 2
  9.             count -= 1
  10.         end
  11.     end
  12.     return true
  13. end
  14.  
  15. def execute(program, nums, operators)
  16.     stack = []
  17.     log = []
  18.     nums = nums.dup
  19.     operators = operators.dup
  20.     program.each do |instruction|
  21.         case instruction
  22.         when :push
  23.             a = nums.pop
  24.             stack.push Rational(a)
  25.             log << "push #{a}"
  26.         when :reduce
  27.             a = stack.pop
  28.             b = stack.pop
  29.             operator = operators.pop
  30.             stack.push a.send(operator, b)
  31.             log << "reduce with #{operator}"
  32.         end
  33.     end
  34.     return stack.last, log
  35. end
  36.  
  37. def log2expr(log)
  38.     stack = []
  39.     log.each do |i|
  40.         case i
  41.         when /^push (.+)/
  42.             stack.push $1
  43.         when /^reduce with (.+)/
  44.             a = stack.pop
  45.             b = stack.pop
  46.             stack.push "(#{a} #{$1} #{b})"
  47.         end
  48.     end
  49.     stack.last
  50. end
  51.  
  52. if ARGV.size < 2
  53.     puts "Usage: ruby1.9.1 #{__FILE__} <target> <num1> [<num2> <num3> ...]"
  54.     exit
  55. end
  56.  
  57. NUMS = ARGV[1..-1].map(&:to_i)
  58. ([:push] * NUMS.size + [:reduce] * (NUMS.size - 1)).permutation do |program|
  59.     next unless validate(program)
  60.     NUMS.permutation do |nums|
  61.         [:+, :-, :*, :/].repeated_permutation(NUMS.size - 1) do |operators|
  62.             begin
  63.                 result, log = execute(program, nums, operators)
  64.                 if result == ARGV[0].to_i
  65.                     puts log
  66.                     puts ""
  67.                     puts "=> #{log2expr(log)}"
  68.                     exit
  69.                 end
  70.             rescue ZeroDivisionError
  71.             end
  72.         end
  73.     end
  74. end
  75.  
  76. puts "No Answer"
Add Comment
Please, Sign In to add comment