Skip to content

Instantly share code, notes, and snippets.

@gartenfeld
Created October 14, 2015 01:13
Show Gist options
  • Save gartenfeld/38a834ee99f1e0dec2ed to your computer and use it in GitHub Desktop.
Save gartenfeld/38a834ee99f1e0dec2ed to your computer and use it in GitHub Desktop.
A space-intensive solution...
// N number of people stand in a circle.
// The people are numbered in order from 1 to N.
// Starting from 1, we remove every other person
// from the circle until there is only one person remaining.
// I would like you to write a function which takes in the number N
// and outputs the number of the last person remaining. For example:
// f(3) outputs 3
// f(4) outputs 1
// f(5) outputs 3
var f = function(N) {
var circle = Array.apply(null, Array(N))
.map(function(item, index) { return index + 1; });
var cursor = 0,
removing = 0;
while (circle.length > 2) {
circle.splice(cursor, removing);
cursor = (cursor + +!removing) % (circle.length);
removing = +!removing;
}
return circle[(cursor + 2) % (circle.length)];
};
// TESTS
console.log(f(3))
console.log(f(4))
console.log(f(5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment