Skip to content

Instantly share code, notes, and snippets.

@waltz
Created December 30, 2019 18:39
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 waltz/ffa288238eb880dbb7f1410b5b488353 to your computer and use it in GitHub Desktop.
Save waltz/ffa288238eb880dbb7f1410b5b488353 to your computer and use it in GitHub Desktop.
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