fork download
  1.  
  2. /*
  3. PROBLEM: Evaluate a Nested Math Expression
  4. FOLLOW-UP 1: Support Decimal Numbers
  5.  
  6. Given a valid nested mathematical expression containing:
  7. - add(x, y)
  8. - sub(x, y)
  9. - mul(x, y)
  10. - div(x, y)
  11. - pow(x, y)
  12.  
  13. Numbers can be positive, negative, integers, or decimals.
  14.  
  15. Examples:
  16. add(2.5,3.5) -> 6
  17. mul(-2.5,4) -> -10
  18. div(7,2) -> 3.5
  19. add(1.5,mul(2.5,2)) -> 6.5
  20. pow(2.5,2) -> 6.25
  21.  
  22. Assumptions:
  23. - Input is syntactically valid.
  24. - Each function takes exactly two arguments.
  25. - Division returns the floating-point quotient.
  26. - Division by zero is not allowed.
  27. - Exponents are nonnegative integers.
  28. - Spaces are allowed around tokens.
  29. - Standard JavaScript Number precision applies.
  30.  
  31. APPROACH: Two Stacks
  32.  
  33. names -> stores pending operations
  34. values -> stores numbers and evaluated results
  35.  
  36. Time: O(n), treating Math.pow as O(1).
  37. Space: O(d), where d is maximum nesting depth.
  38. Worst-case space: O(n).
  39. */
  40.  
  41. function evaluateExpression(s) {
  42. const names = [];
  43. const values = [];
  44.  
  45. let i = 0;
  46.  
  47. // Skip spaces.
  48. function skipSpaces() {
  49. while (i < s.length && s[i] === ' ') {
  50. i++;
  51. }
  52. }
  53.  
  54. // Check if a number starts at the current character.
  55. function isNumberStart(ch) {
  56. return (
  57. ch === '-' ||
  58. ch === '.' ||
  59. (ch >= '0' && ch <= '9')
  60. );
  61. }
  62.  
  63. // Parse a complete number, including decimals.
  64. //
  65. // Examples:
  66. // "12" -> 12
  67. // "-12" -> -12
  68. // "3.14" -> 3.14
  69. // "-2.5" -> -2.5
  70. // ".5" -> 0.5
  71. // "-.75" -> -0.75
  72. // "5." -> 5
  73. function parseNumber() {
  74. const start = i;
  75.  
  76. // Optional negative sign.
  77. if (s[i] === '-') {
  78. i++;
  79. }
  80.  
  81. // Read digits before decimal point.
  82. while (
  83. i < s.length &&
  84. s[i] >= '0' &&
  85. s[i] <= '9'
  86. ) {
  87. i++;
  88. }
  89.  
  90. // Optional decimal point.
  91. if (s[i] === '.') {
  92. i++;
  93.  
  94. // Read digits after decimal point.
  95. while (
  96. i < s.length &&
  97. s[i] >= '0' &&
  98. s[i] <= '9'
  99. ) {
  100. i++;
  101. }
  102. }
  103.  
  104. return Number(s.slice(start, i));
  105. }
  106.  
  107. // Parse add, sub, mul, div, or pow.
  108. function parseOperation() {
  109. const operation = s.slice(i, i + 3);
  110. i += 3;
  111. return operation;
  112. }
  113.  
  114. // Apply an operation to two values.
  115. function applyCall(operation, x, y) {
  116. if (operation === 'add') return x + y;
  117. if (operation === 'sub') return x - y;
  118. if (operation === 'mul') return x * y;
  119.  
  120. // FOLLOW-UP CHANGE:
  121. // Return exact floating-point division.
  122. if (operation === 'div') return x / y;
  123.  
  124. if (operation === 'pow') return Math.pow(x, y);
  125. }
  126.  
  127. // Main iterative parsing loop.
  128. while (i < s.length) {
  129. skipSpaces();
  130.  
  131. if (i >= s.length) break;
  132.  
  133. // Case 1: Number
  134. if (isNumberStart(s[i])) {
  135. values.push(parseNumber());
  136. }
  137.  
  138. // Case 2: Operation
  139. else if (s[i] >= 'a' && s[i] <= 'z') {
  140. names.push(parseOperation());
  141. }
  142.  
  143. // Case 3: Completed function call
  144. else if (s[i] === ')') {
  145. // Pop second argument first (LIFO).
  146. const y = values.pop();
  147. const x = values.pop();
  148.  
  149. const operation = names.pop();
  150.  
  151. const result = applyCall(operation, x, y);
  152.  
  153. values.push(result);
  154.  
  155. i++; // Skip ')'
  156. }
  157.  
  158. // Case 4: Skip '(' or ','
  159. else {
  160. i++;
  161. }
  162. }
  163.  
  164. return values[0];
  165. }
  166.  
  167.  
  168. // ---------------- TEST HARNESS ----------------
  169.  
  170. // Floating-point arithmetic can introduce tiny
  171. // rounding differences, so compare with a tolerance.
  172.  
  173. function approximatelyEqual(a, b) {
  174. return Math.abs(a - b) <=
  175. 1e-9 * Math.max(1, Math.abs(a), Math.abs(b));
  176. }
  177.  
  178. const tests = [
  179. // Basic decimal arithmetic
  180. ["add(2.5,3.5)", 6],
  181. ["sub(5.5,2.25)", 3.25],
  182. ["mul(2.5,4)", 10],
  183. ["div(7,2)", 3.5],
  184.  
  185. // Negative decimals
  186. ["mul(-2.5,4)", -10],
  187. ["add(-1.5,2.75)", 1.25],
  188. ["div(-7,2)", -3.5],
  189.  
  190. // Nested expressions
  191. ["add(1.5,mul(2.5,2))", 6.5],
  192. ["sub(div(7,2),mul(1.5,2))", 0.5],
  193.  
  194. // Decimal powers
  195. ["pow(2.5,2)", 6.25],
  196. ["pow(-1.5,2)", 2.25],
  197. ["pow(5.5,0)", 1],
  198.  
  199. // Decimal syntax
  200. ["add(.5,.25)", 0.75],
  201. ["sub(5.,2.5)", 2.5],
  202. ["add(-.75,1)", 0.25],
  203.  
  204. // Floating-point precision
  205. ["add(0.1,0.2)", 0.3],
  206.  
  207. // Standalone number
  208. ["-3.75", -3.75],
  209.  
  210. // Spaces
  211. ["add( 2.5 , mul( 3 , 1.5 ) )", 7]
  212. ];
  213.  
  214. tests.forEach(([input, expected], index) => {
  215. const actual = evaluateExpression(input);
  216. const passed = approximatelyEqual(actual, expected);
  217.  
  218. console.log(
  219. `Test ${index + 1}: ${passed ? "PASS" : "FAIL"}` +
  220. ` | Expected: ${expected}` +
  221. ` | Actual: ${actual}`
  222. );
  223. });
  224.  
Success #stdin #stdout 0.03s 5624KB
stdin
Standard input is empty
stdout
Test 1: PASS | Expected: 6 | Actual: 6
Test 2: PASS | Expected: 3.25 | Actual: 3.25
Test 3: PASS | Expected: 10 | Actual: 10
Test 4: PASS | Expected: 3.5 | Actual: 3.5
Test 5: PASS | Expected: -10 | Actual: -10
Test 6: PASS | Expected: 1.25 | Actual: 1.25
Test 7: PASS | Expected: -3.5 | Actual: -3.5
Test 8: PASS | Expected: 6.5 | Actual: 6.5
Test 9: PASS | Expected: 0.5 | Actual: 0.5
Test 10: PASS | Expected: 6.25 | Actual: 6.25
Test 11: PASS | Expected: 2.25 | Actual: 2.25
Test 12: PASS | Expected: 1 | Actual: 1
Test 13: PASS | Expected: 0.75 | Actual: 0.75
Test 14: PASS | Expected: 2.5 | Actual: 2.5
Test 15: PASS | Expected: 0.25 | Actual: 0.25
Test 16: PASS | Expected: 0.3 | Actual: 0.30000000000000004
Test 17: PASS | Expected: -3.75 | Actual: -3.75
Test 18: PASS | Expected: 7 | Actual: 7