约瑟夫问题的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