您的位置:首页 > 其它

一群小孩围成一个圈的经典算法

2017-05-20 07:50 537 查看
问题:

一群小孩围成一个圈,设置一个数,这个数是个小于小孩总数大于0的一个整数,从第一个小孩开始报数,当其中一个小孩报到你设置的那个数的时候离开那个圈,这样一来反复报下去,直到只剩下最后一个小孩的时候那个小孩就是胜利者,写程序来找出这个小孩。

import java.util.ArrayList;

public class Test {
static int count=0;
static final int target=3;
public static void main(String args[])
{
ArrayList<Integer> aa=new ArrayList<Integer>();
ArrayList<Integer> delaa=new ArrayList<Integer>();
for(int i=1;i<=50;i++)
{
aa.add(i);
}
System.out.println("the child count is "+50+"");
System.out.println("the target is "+target+"");
while(true)
{
if(aa.size()==1)
{
break;
}
for(Integer a:aa)
{
count++;
if(count==target)
{
count=0;
delaa.add(a);
}
}
for(Integer a:delaa)
{
aa.remove(a);
}
for(int a:aa)
{
System.out.println("a== "+a+"");
}
System.out.println("############################");
}
for(int a:aa)
{
System.out.println("the winer is "+a+"");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: