Quick actions

cmd+k|ctrl+k

Navigation

Languages

Print variations

Snippet info

Language

JavaScript

Visibility

public

Author

beksultan280119

Created

2018-09-05T11:48:09Z

Updated

2018-09-07T07:44:35Z

const NUMS = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const SUM = 100;

function printVariation(allOperators) {
  const joinedNums = [];
  const operators = [];

  // joining numgers
  allOperators.forEach((o, index) => {
    if (o === 'join') {
      if (index) {
        const prevNum = joinedNums[joinedNums.length - 1];
        joinedNums[joinedNums.length - 1] = prevNum * 10 + NUMS[index + 1];
      } else {
        const prevNum = NUMS[index];
        joinedNums.push(prevNum * 10 + NUMS[index + 1]);
      }
    } else {
      if (index === 0) {
        joinedNums.push(NUMS[0]);
      }
      joinedNums.push(NUMS[index + 1]);
      operators.push(o);
    }
  });

  let result = joinedNums[0];
  const sequence = [joinedNums[0]];

  // calculating the result
  operators.forEach((o, index) => {
    if (o == '+') {
      result += joinedNums[index + 1];
    } else {
      result -= joinedNums[index + 1];
    }

    sequence.push(o);
    sequence.push(joinedNums[index + 1]);
  });

  if (result === SUM) {
    console.log(sequence.join(' '));
  }
}

function findVariations(operators = []) {
  if (operators.length >= 8) {
    printVariation(operators);
    return;
  }

  const v1 = operators.slice();
  v1.push('+')
  findVariations(v1);

  const v2 = operators.slice();
  v2.push('-')
  findVariations(v2);

  const v3 = operators.slice();
  v3.push('join')
  findVariations(v3);
}

findVariations();
INFO