Skip to content

Instantly share code, notes, and snippets.

@cortezcristian
Created July 10, 2020 18:44
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 cortezcristian/24a0959ef219f07e493ab1174c32c10c to your computer and use it in GitHub Desktop.
Save cortezcristian/24a0959ef219f07e493ab1174c32c10c to your computer and use it in GitHub Desktop.
Coding the Josephus Problem solution1.js
// My ugly first solution draft
const solution = (n) => {
// Ensure n is number
if (typeof n !== 'number') return 0;
// Ensure n is > 0
if (n < 1) return 0;
// This array represents the circle
const arr = [];
// Fill the array with 1 ones to begin
// 1 - means alive
// 0 - means elminated
for (let i = 0; i < n; i++) arr[i] = 1;
// Iterate until the sum of the array is 1,
// which means 1 is the last man standing
while (arr.reduce((a, b) => a + b, 0) !== 1) {
// Find who is the next guy alive and standing to the left
for (let i = 0; i < n; i++) {
// Find a living soldier
if (arr[i] === 1) {
// Split the circle in two segments
let after = arr.slice(i+1, arr.length);
let before = arr.slice(0, i);
// Find the next guy alive
if (after.reduce((a, b) => a + b, 0) > 0) {
let nextAliveIndex = i + 1 + after.findIndex((a) => a === 1);
// Eliminate
arr[nextAliveIndex] = 0;
} else if (before.reduce((a, b) => a + b, 0) > 0) {
let nextAliveIndex = before.findIndex((a) => a === 1);
// Eliminate
arr[nextAliveIndex] = 0;
}
}
}
}
// As position in the diagram start from 1
return 1 + arr.findIndex((a) => a === 1);
}
const position = solution(5);
console.log(position); // >>> 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment