Created
December 30, 2019 18:39
-
-
Save waltz/ffa288238eb880dbb7f1410b5b488353 to your computer and use it in GitHub Desktop.
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
const possibleBalance = (program, targetValue) => { | |
program = program.split(''); | |
for (let i = program.length; i > 0; i--) { | |
let currentSum = 0; | |
currentSum = sum(program.slice(0, i)); | |
if (currentSum >= targetValue) { | |
return program.length - i; | |
} | |
} | |
return -1; | |
} | |
const sum = (prog) => { | |
let count = 0; | |
prog.forEach(char => { | |
if (char === '+') { | |
count += 1; | |
} else if (char === '-') { | |
count -= 1; | |
} else { | |
console.log('error!'); | |
} | |
}) | |
return count; | |
} | |
// test cases | |
console.log(possibleBalance("+++-++-++--+-++++-+--++-++-+-++++-+++--", 12) == 1); | |
console.log(possibleBalance("+++-++-++--+-++++-+--++-++-+-++++-+++--", 13) == 2); | |
console.log(possibleBalance("+++-++-++--+-++++-+--++-++-+-++++-+++--", 14) == -1); | |
console.log(possibleBalance("+++---", 3) == 3); | |
console.log(possibleBalance("+++-+---", 3) == 3); | |
console.log(possibleBalance("----+-", -2) == 4); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment