Skip to content

Instantly share code, notes, and snippets.

@kcparashar
Created March 30, 2018 00:25
Show Gist options
  • Select an option

  • Save kcparashar/8263e37e6cd0106ee033d0dabc91ac2b to your computer and use it in GitHub Desktop.

Select an option

Save kcparashar/8263e37e6cd0106ee033d0dabc91ac2b to your computer and use it in GitHub Desktop.
Non working attempt for Ampersand JS Coding Challenge
// Given a string of numbers and operators,
// print out all the different ways you can add parentheses
// to force the order of operations to be explicit,
// and the result for running the operations in that order.
// No weird inputs, everything is separated by one space.
// Supported operators are +, *, -, = (for the = operator, if the values are the same return 1, otherwise return 0)
// Print your results sorted numerically
// Don't worry about the input expression size being too large
// Your code should be written in javascript
// Don't use eval or external libraries
// node test.js "2 - 1 - 1"
// ((2-1)-1) = 0
// (2-(1-1)) = 2
// node test.js "2 * 3 - 4 * 5";
// (2*(3-(4*5))) = -34
// ((2*3)-(4*5)) = -14
// ((2*(3-4))*5) = -10
// (2*((3-4)*5)) = -10
// (((2*3)-4)*5) = 10
// node test.js "2 + 2 = 2"
// ((2+2)=2) = 0
// (2+(2=2)) = 3
input = process.argv.slice(2)[0] // make sure this works across systems
var solns = {}; // e.g. {-34: (2*(3-(4*5)))}
function evaluate(a, op, b) {
switch(String(op)) {
case '+':
return(a + b)
break;
case '-':
return(a - b)
break;
case '*':
return(a * b)
break;
case '=':
if (a == b) {
return(1)
}
return(0)
break;
}
}
function diffParentheses(input) {
input = input.replace(/\s/g, '') // Strips spaces from input for simplicity
var ans = []
if (ans.length == 0) {
ans.push(input)
}
for (var i = 0; i < input.length; i++) {
if (~'+-*='.indexOf(input[i])) {
var left = diffParentheses(input.substring(0, i));
var operator = input[i];
var right = diffParentheses(input.substring(i + 1));
ans.push("(" + left + ")" + operator + "(" + right + ")")
console.log(ans);
}
}
return input;
}
diffParentheses(input);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment