I was asked this in an interview but got the an answer wrong. I tried to figure it out later and send them the response but it was still wrong. Can someone point me in the right direction or let me know what I'm doing wrong? Thanks.
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.
import java.util.*;
import java.lang.*;
/**
* Class to solve 'Chairs' problem, written by Renee MacDonald (rm97851@gmail.com)
*/
public class LeaveRoom{
/**
* For 'Chairs' problem, prints the resulting final chair.
*
* @param args optional startup arguments; not used
* @return null
*/
public static void main(String []args){
int numChairs = 100;
LinkedList<Integer> list = new LinkedList();
for (int i=1; i<=numChairs; i++){
list.add(i);
}
int pos=0; // Position, i.e. where we are in the circle of chairs
int skip=0; // Number to of chairs to skip
int modResult;
try {
while (list.size()>1){
modResult = ((pos+skip) % list.size()); // Simulate traveling around the circle, whose size just changed
System.out.println("about to remove chair numbered " + list.get(modResult));
list.remove(modResult);
System.out.println("pos = " + pos);
System.out.println("skip = " + skip);
System.out.println("pos+skip = " + (pos+skip));
System.out.println("removed element " + modResult);
System.out.println();
System.out.println("new list size = " + list.size());
pos += skip;
pos = pos % (list.size()+1); // If we went beyond PRIOR list size, go around circle
skip ++; // First skip 1, then 2, then 3, ...
}
System.out.println("remaining one is chair # " + list.get(0));
System.out.println();
}
catch (IllegalArgumentException e){
System.out.println("exception occurred, e=" + e);
}
}
}