fork download
  1. BEGIN {
  2. stack[0] = 0
  3. stack_p = 0
  4.  
  5. print rpn_calc("3 19 + -2 /")
  6. print rpn_calc("3 19 + -2 / +")
  7. print rpn_calc("1 2 + 3 4 5 sum")
  8. print rpn_calc("5 4 - exp")
  9. print rpn_calc("1 2.0 +")
  10. print rpn_calc("12 5 /")
  11. print rpn_calc("2 3 4 prod")
  12. }
  13.  
  14. function rpn_calc(str, i, n, q, ql, t) {
  15.  
  16. ql = split(str, q)
  17. if (! is_integer(q[1])) return 0
  18. n = q[1]
  19.  
  20. init()
  21. for(i = 2; i <= ql; i++) {
  22. t = q[i]
  23. if (is_integer(t)) {
  24. push(n)
  25. n = t
  26. }
  27. else if (t == "+") {
  28. if (empty()) return 0
  29. n += pop()
  30. }
  31. else if (t == "-") {
  32. if (empty()) return 0
  33. n = pop() - n
  34. }
  35. else if (t == "*") {
  36. if (empty()) return 0
  37. n *= pop()
  38. }
  39. else if (t == "/") {
  40. if (empty()) return 0
  41. n = int(pop() / n)
  42. }
  43. else if (t == "exp") {
  44. n = exp(n)
  45. }
  46. else if (t == "sum") {
  47. while(! empty()) {
  48. n += pop()
  49. }
  50. }
  51. else if (t == "prod") {
  52. while(! empty()) {
  53. n *= pop()
  54. }
  55. }
  56. else {
  57. return "error"
  58. }
  59. }
  60.  
  61. return n
  62. }
  63.  
  64. function is_integer(s) {
  65. return match(s, /^-?(0|[1-9][0-9]*)$/)
  66. }
  67.  
  68. function init( n) {
  69. stack_p = 0
  70. }
  71.  
  72. function push(n) {
  73. stack[stack_p++] = n
  74. }
  75.  
  76. function empty( n) {
  77. return (stack_p < 1);
  78. }
  79.  
  80. function pop( n) {
  81. return (empty() ? 0 : stack[--stack_p])
  82. }
  83.  
Success #stdin #stdout 0.01s 4232KB
stdin
Standard input is empty
stdout
-11
0
15
2.71828
error
2
24