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) {
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 ]


Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store