约瑟夫问题的java实现

约瑟夫问题,又称丢手帕问题。试着实现了一下,实现逻辑简单,没有复杂的算法,适合新手参考。

 

//参数step指步进值,步进到几则出列
    //参数count指共有几个人
    public static int diuShouPa(int step, int count) {
        
        //用List模拟一个队列
        List<Integer> queue = new ArrayList<Integer>();
        for (int i = 1; i <= count; i++) {
            queue.add(i);
            System.out.println("报数:" + i);
        }
//loopIndex:队列在while循环中的坐标
        int loopIndex=0;
        while (true) {
            //t:用来记录有没有循环够step次
            int t = 1;
            //这一层while用来步进step次
            while(t<=step) {
                
                // 如果循环到了队列末尾,则从坐标1开始循环
                if (loopIndex > queue.size()-1) {
                    loopIndex = 0;
                }

                // 如果循环了了step次,则说明loopIndex这个坐标上的项要出列,移除该项
                if (t == step) {
                    System.out.println("出列:"+queue.get(loopIndex));
                    queue.remove(loopIndex);
                }else{
                    //只有在没有移除项(出列)时循环坐标才++,当你移除了一项时,集合里后面的对象会往前补,所以坐标不需要++
                    loopIndex++;
                }
                t++;
            }

            //如果集合的size不够一次步进了,则返回最后一个出列的对象
            if (queue.size() < step) {
                return loopIndex;
            }
        }
  }

 

转载于:https://www.cnblogs.com/2333/p/5766088.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值