Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- document.write(JSON.stringify(getCombinations(26, 3)));
- /*
- * For example, if target=26 and singleNum=3,
- * the answer is 3*3*3 - 3/3
- */
- function getCombinations(target, singleNum) {
- var queue = [];
- var visited = {};
- queue.push({curVal: singleNum, last: singleNum, operators: []});
- while (queue.length > 0) {
- var node = queue.shift();
- // can't use curVal because for target=8 (3*3-3/3) the loop
- // will stop at 3*3-3=6 because 6 was visited by 3+3 earlier
- var visitedKey = node.curVal + '_' + node.last;
- if (visited[visitedKey]) {
- continue;
- }
- visited[visitedKey] = true;
- if (node.curVal == target) {
- return node.operators;
- }
- // maybe there is a better condition to stop the search
- // but this works
- if (node.curVal < 0 || node.curVal > target * singleNum) {
- continue;
- }
- // check * operator
- queue.push({
- curVal: node.curVal - node.last + node.last * singleNum,
- last: node.last * singleNum,
- operators: node.operators.concat(['*'])
- });
- // check + operator
- queue.push({
- curVal: node.curVal + singleNum,
- last: singleNum,
- operators: node.operators.concat(['+'])
- });
- // check - operator
- queue.push({
- curVal: node.curVal - singleNum,
- last: -singleNum,
- operators: node.operators.concat(['-'])
- });
- // check / operator
- if (node.last % singleNum == 0) {
- queue.push({
- curVal: node.curVal - node.last + node.last / singleNum,
- last: node.last / singleNum,
- operators: node.operators.concat(['/'])
- });
- }
- }
- return [];
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement