码迷,mamicode.com
首页 > 编程语言 > 详细

约瑟夫问题的java实现

时间:2016-08-12 19:56:37      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

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

 

//参数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;
            }
        }

 

约瑟夫问题的java实现

标签:

原文地址:http://www.cnblogs.com/zsmart/p/5766088.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!