N个人编号从1到N,围成一个圆圈。从1号开始传递一个热土豆。经过M次传递后拿着热土豆的人被清除离座,围坐的人圆圈缩紧,由坐在被清除的人后面的人拿起热土豆继续进行游戏。最后剩下的一个人取胜。
如果M=0和N=5,则游戏人依序被清除,5号游戏人获胜。
如果M=1和N=5,那么被清除人的顺序是2,4,1,5。拿位高手可以替偶写个程序让偶参考一下,偶写了很久了还不好使。谢谢啦
如果M=0和N=5,则游戏人依序被清除,5号游戏人获胜。
如果M=1和N=5,那么被清除人的顺序是2,4,1,5。拿位高手可以替偶写个程序让偶参考一下,偶写了很久了还不好使。谢谢啦
// 你的参数
int M = 1;
int N = 5;
// 初始化
List<Integer> people = new LinkedList<Integer>();
for(int i=0;i<N;i++){
people.add(i+1);
}
//开始剔除
System.out.print("Removed ");
int pos = 0;
while(people.size() > 1){
pos = (pos+M)%people.size();
System.out.print(people.remove(pos)+", ");
}
//打印结果
System.out.println("\nThe last winner: "+people.get(0));
}M=0,N=5,运行结果
Removed 1, 2, 3, 4,
The last winner: 5M=1,N=5,运行结果
Removed 2, 4, 1, 5,
The last winner: 3
public static void main(String[] args){
new JesephRing().getWinner(5,1);
}
public int getWinner(int N,int M){
int n=N;
int m=M;
int count=1;
int[] a=new int[n];
for(int i=0;n>=1;i=(i+1)%5){
if(a[i]==0){
a[i]=i+1;
}
if(a[i]==-1){
continue;
}
if(n==1){
System.out.println(a[i]+"号获胜");
return a[i];
}
if(count%(m+1)==0){
System.out.println("第"+a[i]+"个人清除离座");
n--;
a[i]=-1;
count=1;
}else{
count++;
}
}
return 0;
}}试试这个