我在接受采访时被问到这个问题,但答案错了。我试图稍后解决它并向他们发送响应,但它仍然是错误的。有人能指出我正确的方向或让我知道我做错了什么?感谢。
花点时间想象你在一个有100把椅子的房间里 排列成一个圆圈。这些椅子从One顺序编号 到一百个。
在某个时间点,第1号椅子上的人将被告知离开 房间。第2号椅子上的人将被跳过,而人员将被跳过 椅子#3将被告知离开。旁边去的是椅子#6的人。在 换句话说,最初会跳过1个人,然后是2,3,4 .. 等等。这种跳过模式将继续绕圈 直到只剩下一个人......幸存者。请注意 当这个人离开房间时,椅子会被移除。
写一个程序来确定幸存者所在的椅子。
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);
}
}
}