Guest User

Untitled

a guest
Jun 21st, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. class StrawpigScript
  2. attr_accessor :script
  3.  
  4. TOKENS = ["+", "-", "*", "/", "x", "integer", "float"]
  5.  
  6.  
  7. def initialize(length)
  8. intermediate = length.times.inject("") {|program, i| program + " #{TOKENS.sample}"}
  9. with_ints = intermediate.gsub(/integer/) {rand(21)-10}
  10. @script = with_ints.gsub(/float/) {(rand*20.0-10.0).round(2)}
  11. end
  12.  
  13.  
  14. def evaluate(x)
  15. stack = []
  16. @script.split.each do |token|
  17. begin
  18. case token
  19. when /([-+]?[0-9]*\.?[0-9]+)/ # float
  20. stack.push($1.to_f)
  21. when /[-+]?[0-9]+/ # integer
  22. stack.push($1.to_i)
  23. when "+", "-", "*"
  24. raise ArgumentError, "short stack" if stack.length < 2
  25. arg1, arg2 = stack.pop(2)
  26. result = arg1.send(token.intern, arg2)
  27. stack.push(result)
  28. when "/"
  29. raise ArgumentError, "short stack" if stack.length < 2
  30. arg1, arg2 = stack.pop(2)
  31. result = (arg2 == 0) ? 0 : arg1.send(token.intern, arg2)
  32. stack.push(result)
  33. when "x"
  34. stack.push x
  35. else
  36. # ignore unrecognized tokens
  37. end
  38. rescue ArgumentError => e
  39. # don't pop items from the stack
  40. end
  41. end
  42. return stack[-1] || 1000000 # the top stack item, or a huge value if it's missing
  43. end
  44. end
Add Comment
Please, Sign In to add comment