Last active
October 31, 2018 08:31
-
-
Save spirinvladimir/847fdde3c3701d6a27ea85fa187a7678 to your computer and use it in GitHub Desktop.
Solution for task "Sum 100" by https://www.diginex.com
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*Question 1: Sum to 100 | |
Write a function that, given a string of digits, build an expression such that the digits will sum to 100 by inserting +, - anywhere between the digits. | |
For example, given the input 123456789, one such expression is 1 + 23 - 4 + 5 + 6 + 78 - 9 = 100 | |
Your function should return all possible combinations. | |
*/ | |
var results = {}; | |
function calc(n, s, part) { | |
if (n === 0 && s === '' && part[0] !== '-') return results[part.substring(1)] = null | |
if (Math.abs(n) > (1 + Number(s[0])) * Math.pow(10, s.length - 1)) return;// extra line for optimization | |
for (var i = 1; i <= s.length; i++) { | |
var a = Number(s.substring(0, i)) | |
calc(n - a, s.substring(i), part + '+' + a) | |
calc(n + a, s.substring(i), part + '-' + a) | |
} | |
} | |
calc(100, '123456789', '') || Object.keys(results).map(r => console.log(r)) | |
/* | |
1+2+3-4+5+6+78+9 | |
1+2+34-5+67-8+9 | |
1+23-4+5+6+78-9 | |
1+23-4+56+7+8+9 | |
12+3+4+5-6-7+89 | |
12+3-4+5+67+8+9 | |
12-3-4+5-6+7+89 | |
123+4-5+67-89 | |
123-4-5-6-7+8-9 | |
123+45-67+8-9 | |
123-45-67+89 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment