Skip to content

Instantly share code, notes, and snippets.

@softwarespot
Created October 11, 2015 07:15
Show Gist options
  • Save softwarespot/e1c1c02d4cb0510bc031 to your computer and use it in GitHub Desktop.
Save softwarespot/e1c1c02d4cb0510bc031 to your computer and use it in GitHub Desktop.
Example of Josephus problem
function josephus(array, count) {
// Return store
const store = [];
// Counter for each time the element should be spliced
let counter = 0;
// Array index position
let index = 0;
while (array.length > 0) {
// This is because 'array' is treated like a circular array
index = index % array.length;
if (++counter === count) {
// Remove the element from the array and push onto the store.
// The first element is used, hence [0]
store.push(array.splice(index, 1)[0]);
// Reset the counter
counter = 0;
// Move back one index value
index--;
}
index++;
}
return store;
}
// Example
console.log(josephus([1, 2, 3, 4, 5, 6, 7], 3));
console.log(josephus([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment