Jason Knight
2 min readJul 11, 2020

If you did a “Array(N)” you could leverage their empty state as your trigger skipping the pointless inner loop.

If you have multiple var in a row don’t say var for each, comma delimit instead.

When you have a perfectly good condition loop on the condition instead of while(true), 99% of the time you see while(true) you’re looking at flawed or broken logic.

But most of all, you reference a variable K that doesn’t exist. Did you mean M which you didn’t use? This is just part of why no matter how much “at the blackboard” math wankers LOVE their single letter variables, they just encourage making mistakes on any real-world task.

Don’t even get me started on the pointless use of CONST doing a normal function’s job or the omission of semi-colons begging for code fragility.

And your solution doesn’t even work, since if M is actually your K, you’re not incrementing by that around the circle, nor are you compensating for hits in the pool.

Thus in your example of 11,3 should be returning [ 8, 4, 10, 1, 7, 6, 2, 11, 9, 3, 6 ] but your logic is flawed.

function joseph(numPrisoners, skip) {
var
result = Array(numPrisoners),
dead = 0,
finger = 0;
while (dead < numPrisoners) {
var i = skip;
// skip ahead
do {
finger = (finger + 1) % numPrisoners;
// only count the living
if (!result[finger]) i--;
} while (i);
// if we landed on the dead, skip ahead to the next living
while (result[finger]) finger = (finger + 1) % numPrisoners;
result[finger] = ++dead;
}
return result;
}
console.log(joseph(11,3)); // [ 8, 4, 10, 1, 7, 6, 2, 11, 9, 3, 6 ]

See?

Jason Knight

Accessibility and Efficiency Consultant, Web Developer, Musician, and just general pain in the arse