package com.itheima;
import java.util.ArrayList;
import java.util.List;
/*
* 10、 有100个人围成一个圈,从1开始报数,报到14的这个人就要退出。然后其他人重新开始,从1报数,到14退出。问:最后剩下的是100人中的第几个人?
*/
public class Test10 {
public static void main(String[] args) {
Circle c = new Circle();
c.exits2();
}
}
class Circle{
private List<Integer> queue = new ArrayList<Integer>(); //队列
private int maxIndex = 0; //最大索引值
private int currentIndex = 0; //当前索引值
//第一种方法
public void exit()
{
//生成队列
for(int i=1; i<=100; i++)
{
queue.add(i);
}
maxIndex = queue.size() - 1;
while(queue.size() > 1)
{
for(int j=1; j<=14; j++)
{
//如果当前索引大于了最大索引,说明已经数到最后一个号,重新数
if(currentIndex > maxIndex)
{
currentIndex = 0;
}
System.out.println("第" + queue.get(currentIndex) + "号,数" + j);
if(j==14)
{
System.out.println("第" + queue.remove(currentIndex) + "号退出"); //去除当前索引的值,将队列的后面的值都提前一个索引
System.out.println("当前存在的号为:" + queue);
maxIndex--; //最大索引减一,currentIndex当前索引不变,即将队列后面一个号,作为当前的索引值
}
else
{
currentIndex++; //每循环一次,当前的索引就会加一,跳到队列中的下个数
}
}
}
}
//第二种方法
public void exits2()
{
boolean[] queue = new boolean[100];
for(int i=0;i<queue.length;i++)
{
queue[i] = true;
}
int len = queue.length;
int count = 0;
while(len>1)
{
for(int i=0;i<queue.length;i++)
{
if(queue[i]==true)
{
count++;
if(count == 14)
{
queue[i] = false;
count=0;
len--;
}
}
}
}
for(int i=0;i<queue.length;i++)
{
System.out.println(i + " : " + queue[i]);
}
}
}
有100个人围成一个圈,从1开始报数,报到14的这个人就要退出
最新推荐文章于 2022-10-25 08:36:55 发布