Skip to content

Instantly share code, notes, and snippets.

@mvasilkov
Created February 12, 2020 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvasilkov/f437a89020336fed68a95cdfd55bf6f8 to your computer and use it in GitHub Desktop.
Save mvasilkov/f437a89020336fed68a95cdfd55bf6f8 to your computer and use it in GitHub Desktop.
'use strict'
const assert = require('assert').strict
/**
* Write a program that outputs all possibilities to put + or - or nothing
* between the numbers 1, 2, ..., 9 (in this order) such that the result
* equals 100. For example: 1 + 2 + 34 – 5 + 67 – 8 + 9 = 100.
*/
// Brute force solution: check all variants,
// print those that end up being equal to 100.
/**
* @param {number[]} numbers Remaining numbers: [7, 8, 9]
* @param {string} resultString Result in readable form: '1 + 23 - 4'
* @param {number} result Result without the last operand
* @param {number} x The last operand
*/
function put(numbers, resultString, result, x) {
// Nothing to do
if (numbers.length === 0) {
// Found a solution
if (result + x === 100) {
console.log(`${resultString} == 100`)
// Sanity check
assert.strictEqual(eval(resultString), 100)
}
return
}
const n = numbers[0]
// Put +
put(numbers.slice(1), `${resultString} + ${n}`, result + x, n)
// Put -
put(numbers.slice(1), `${resultString} - ${n}`, result + x, -n)
// Put nothing (concat)
put(numbers.slice(1), `${resultString}${n}`, result, 10 * x + Math.sign(x) * n)
}
// We put 1 in there by default, since it always starts with 1.
put([2, 3, 4, 5, 6, 7, 8, 9], '1', 0, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment