Advertisement
beautyandfear

Get Target Number Using Single Number and Operations *+-/

Oct 17th, 2018
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. document.write(JSON.stringify(getCombinations(26, 3)));
  2.  
  3. /*
  4.  * For example, if target=26 and singleNum=3,
  5.  * the answer is 3*3*3 - 3/3
  6.  */
  7. function getCombinations(target, singleNum) {
  8.   var queue = [];
  9.   var visited = {};
  10.   queue.push({curVal: singleNum, last: singleNum, operators: []});
  11.  
  12.   while (queue.length > 0) {
  13.     var node = queue.shift();
  14.     // can't use curVal because for target=8 (3*3-3/3) the loop
  15.     // will stop at 3*3-3=6 because 6 was visited by 3+3 earlier
  16.     var visitedKey = node.curVal + '_' + node.last;
  17.     if (visited[visitedKey]) {
  18.         continue;
  19.     }
  20.     visited[visitedKey] = true;
  21.    
  22.     if (node.curVal == target) {
  23.       return node.operators;
  24.     }
  25.     // maybe there is a better condition to stop the search
  26.     // but this works
  27.     if (node.curVal < 0 || node.curVal > target * singleNum) {
  28.       continue;
  29.     }
  30.    
  31.     // check * operator
  32.     queue.push({
  33.       curVal: node.curVal - node.last + node.last * singleNum,
  34.       last: node.last * singleNum,
  35.       operators: node.operators.concat(['*'])
  36.     });
  37.     // check + operator
  38.     queue.push({
  39.       curVal: node.curVal + singleNum,
  40.       last: singleNum,
  41.       operators: node.operators.concat(['+'])
  42.     });
  43.     // check - operator
  44.     queue.push({
  45.       curVal: node.curVal - singleNum,
  46.       last: -singleNum,
  47.       operators: node.operators.concat(['-'])
  48.     });
  49.     // check / operator
  50.     if (node.last % singleNum == 0) {
  51.       queue.push({
  52.         curVal: node.curVal - node.last + node.last / singleNum,
  53.         last: node.last / singleNum,
  54.         operators: node.operators.concat(['/'])
  55.       });
  56.     }
  57.   }
  58.   return [];
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement