多个人围成一圈报数,数到固定值的人出列,求最后剩下的人

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">1.问题描述</span>

多个人围成一圈,按顺序排号,从某一个人开始进行报数,报数为某固定值的人退出圈子,则最后留下的人是原来的哪号人

2.算法解析

新建数组,将符合条件的人出列,剩下的最后一个人是符合条件的人

3.算法编写

	//n个人围成一个圈,从第start人开始报数1,数到mark的人退出,继续数,直到最后剩一个人,获取最后一个人序列号
	public static int getLastNum(final int n,int mark,int start){
		LinkedList<Integer> list=new LinkedList<Integer>();
		for (int i = 1; i <=n; i++) 
			list.add(i);
		int index=start-1;//第几个人开始报数
		while(list.size()>1){
			index+=mark-1;//删除后元素都往前移动了一位
			if(index>=list.size())
				index%=list.size();
			list.remove(index);
		}
		return list.get(0);
	}


4.算法测试

<span style="white-space:pre">	</span>public static void main(String[] args) {
		Random random=new Random();
		int count=20;//测试20组数据
		while (count-->0) {
			int n=random.nextInt(50)+1;//最少一个人
			int mark=random.nextInt(100)*n/100+1;//最少为1
			int start=random.nextInt(100)*n/100+1;//最少从第一个人开始
			System.out.printf("n:%-3d mark:%-3d start:%-3d\nlast:%-3d\n",n,mark,start,getLastNum(n, mark,start));
		}
	}


5.测试结果校验

n:40  mark:34  start:12 
last:35 
n:50  mark:40  start:23 
last:14 
n:20  mark:19  start:9  
last:19 
n:39  mark:28  start:7  
last:11 
n:38  mark:29  start:27 
last:5  
n:9   mark:8   start:8  
last:1  
n:18  mark:16  start:14 
last:3  
n:34  mark:4   start:11 
last:32 
n:31  mark:4   start:17 
last:26 
n:18  mark:9   start:16 
last:5  
n:25  mark:13  start:1  
last:14 
n:10  mark:7   start:2  
last:10 
n:47  mark:16  start:42 
last:47 
n:46  mark:24  start:29 
last:35 
n:28  mark:27  start:1  
last:25 
n:30  mark:29  start:1  
last:25 
n:10  mark:4   start:10 
last:4  
n:40  mark:19  start:11 
last:16 
n:40  mark:5   start:22 
last:37 
n:16  mark:16  start:7  
last:1  





  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值