Created
October 14, 2015 01:13
-
-
Save gartenfeld/38a834ee99f1e0dec2ed to your computer and use it in GitHub Desktop.
A space-intensive solution...
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
// 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