Skip to content

Instantly share code, notes, and snippets.

@scottrice10
Created March 14, 2015 20:45
Show Gist options
  • Select an option

  • Save scottrice10/e48c1ee3a91ec36ade19 to your computer and use it in GitHub Desktop.

Select an option

Save scottrice10/e48c1ee3a91ec36ade19 to your computer and use it in GitHub Desktop.
100 chairs
//Problem: variation of Josephus problem
// Take a second to imagine that you are in a room with 100 chairs arranged in a circle.
//These chairs are numbered sequentially from One to One Hundred.
//At some point in time, the person in chair #1 will be told to leave the room.
//The person in chair #2 will be skipped, and the person in chair #3 will be told to leave.
//Next to go is person in chair #6. In other words, 1 person will be skipped initially, and then 2, 3, 4.. and so on.
//This pattern of skipping will keep going around the circle until there is only one person remaining.. the survivor.
//Note that the chair is removed when the person leaves the room.
//
//Write a program to figure out which chair the survivor is sitting in.
var findLastSurvivingChair = function(noOfChairs) {
noOfChairs = noOfChairs || 100;
//create an empty chair array
var chairArray = [];
// loop from 1 to number of chairs (100) to create array of chairs #1 - #100
for (var i = 1; i <= noOfChairs; i++) {
chairArray.push(i);
}
// Skip starts at 1 and increments by 1 each time a chair is removed
// Continue to remove chairs in while loop until chair array contains one lone surviving chair
var currentIndex = 0;
var skip = 0;
while (chairArray.length > 1) {
chairArray.splice(currentIndex, 1);
skip += 1;
currentIndex += skip;
//if current index becomes greater than number of remaining chairs,
//then set current index to remainder from current index / number of chairs
currentIndex %= chairArray.length;
}
return chairArray[0];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment