Friday, 6 September 2013

Practice quiz for looping over numbers, teacher insist I'm wrong, but I think not

Practice quiz for looping over numbers, teacher insist I'm wrong, but I
think not

So this is the question that is given.
You are in a room with a circle of 100 chairs. The chairs are numbered
sequentially from 1 to 100.
At some point in time, the person in chair #1 will be asked to leave. The
person in chair #2 will be skipped, and the person in chair #3 will be
asked to leave. This pattern of skipping one person and asking the next to
leave will keep going around the circle until there is one person left…
the survivor.
And this is the answer I came up with. I believe this is the right answer,
but the teacher insist it's not. I've done it on paper about 10 times as
well and came up with 74 every time. Is this a trick question or
something? Because I'm not sure what to do from here.
Here is the jsfiddle http://jsfiddle.net/cQUaH/
var console = {
log : function(s) {
document.body.innerHTML += s + "<br>";
}
};
var chairArr = [];
for (var i = 1; i <= 100; i++){
chairArr.push(i);
}
var j = 2;
while(chairArr.length > 1) {
console.log('removing ' + chairArr[j]);
chairArr.splice(j, 1);
j++;
if(j >= chairArr.length) {
console.log('--- Finished pass');
console.log('--- Array state:');
console.log(chairArr);
j = (j == chairArr.length) ? 0 : 1;
}
}
console.log('--- Final result: ' + chairArr);
//result 74

No comments:

Post a Comment