Created
October 11, 2015 07:15
-
-
Save softwarespot/e1c1c02d4cb0510bc031 to your computer and use it in GitHub Desktop.
Example of Josephus problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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