Josephus Problem - Off By One
See original GitHub issueAffected page https://www.freecodecamp.org/learn/coding-interview-prep/rosetta-code/josephus-problem
Your code
function josephus(init, kill) {
// Setup
let currPrisoner = 0;
const prisoners = Array(init).fill(true);
// Execute prisoners
console.log("Kill Sequence:");
for (let numAlive = init; numAlive > 1; numAlive--) {
// Find next prisoner
for (let numSkip = kill; numSkip > 0; numSkip--) {
do {
currPrisoner = (currPrisoner + 1) % init;
} while (!prisoners[currPrisoner]);
}
// Execute prisoner
console.log(currPrisoner);
prisoners[currPrisoner] = false;
}
// Return last man standing
console.log("Last Man Standing:");
console.log(prisoners.indexOf(true));
return prisoners.indexOf(true);
}
josephus(5, 2);
Expected behavior The code that passes the test suite (given above) provides different output than the traditional description of the problem. I think the test suite has an ‘off by one’ error in initializing the starting position.
Current output with solution that passes test suite:
Kill Sequence:
2
4
1
0
Last Man Standing:
3
Expected output per problem description:
Kill Sequence:
1
3
0
4
Last Man Standing:
2
Relevant portion of problem description:
For example, if there are n=5 prisoners and k=2, the order the prisoners are killed in (let’s call it the “killing sequence”) will be 1, 3, 0, and 4, and the survivor will be 2.
See also discussion here: https://forum.freecodecamp.org/t/solution-to-rosetta-code-challenge-josephus-problem/460203
Proposed Fix Change test suite to
josephus(30,3)
should return28
josephus(30,5)
should return2
josephus(20,2)
should return8
josephus(17,6)
should return1
josephus(29,4)
should return1
Bug reported by jsdisco on the forum.
Issue Analytics
- State:
- Created 2 years ago
- Comments:10 (10 by maintainers)
Top GitHub Comments
I agree that the original solution is pretty convoluted.
@alirezaghey, You can always open a PR. After that, we can give feedback and suggest changes if needed.