Last active
April 27, 2017 06:43
-
-
Save juanandresnyc/b21929fbba4d8252edaa to your computer and use it in GitHub Desktop.
find all combinations in '123456789' that lead to 100 with +/- opts (hint: DFS)
This file contains 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
// https://blog.svpino.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour | |
// Answer to prob#5 | |
function dfs(currentPath, currentValue, str) { | |
var strLen = str.length; | |
if (strLen < 2) { | |
if (strLen === 0 || str === '') { | |
if (currentValue === 100) console.log(currentPath); | |
} else { | |
var lastValue = parseInt(str, 10); | |
if (currentValue + lastValue === 100) { | |
console.log(currentPath + ' + ' + str); | |
} else if (currentValue - lastValue === 100) { | |
console.log(currentPath + ' - ' + str); | |
} | |
} | |
return; | |
} | |
for (var i = 1; i <= strLen; i++) { | |
var valueStr = str.substring(0, i); | |
var value = parseInt(valueStr, 10); | |
var remainingStr = str.substring(i, strLen); | |
if (currentPath === '') { | |
dfs(valueStr, currentValue + value, remainingStr); | |
continue; | |
} | |
dfs(currentPath + ' + ' + valueStr, currentValue + value, remainingStr); | |
dfs(currentPath + ' - ' + valueStr, currentValue - value, remainingStr); | |
} | |
} | |
dfs('', 0, '123456789'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Solutions (11)