Java 实现约瑟夫环问题

1.循环报数游戏,有n个人,从1到k报数,报道k 的退出游戏,得出最后获胜人的编号,编号从0开始。
思路:
一.创建大小为 n 的boolean类型的数组,并把所有元素初始化为true;
二.使用while循环,循环的条件为获胜的人数大于1。从0下标位置开始循环判断,这里分为三种情况:
1.index位置的值为true ,且count ==k ,这种情况是找到了退出游戏的人。则把这个位置的值改为false;活着的人数减一,计数继续从1开始计数。
2.index位置的值为true,且count != k;这种情况是还没有找到k位置的人,则继续报数,index++,count++;
3.index位置的值为false ,这种情况是index位置的人已经退出游戏,则count不需要加加,index++就行。
三.找到数组里唯一一个值是true的下标并返回;
下面是代码实现:

public static int CyclicGame(int n, int key) {
        //创建一个大小为 n 的boolean类型数组,所有元素初始化为true;
        boolean[] array = new boolean[n];
        for (int i=0; i<n; i++) {
            array[i]=true;
        }
        //count 报数,index 数组下标,peopleLeft 活着的人数。
        int count = 1;
        int index = 0;
        int peopleLeft = n;
        //只要活着的人大于1就继续循环。
        while (peopleLeft >= 2) {
            //如果index下标的值为true且满足报数到k。则把这个下标的值改为flase;
            //则活着的人peopleLeft--,报数继续从1 开始报数 count =1;
            if (array[index] == true && count == key) {
                array[index] = false;
                peopleLeft --;
                count = 1;

            } else if (array[index] && count != key) {
                //如果index下标的值为true 且count 的值不为k。则count++;index++;
                count ++;
                index = (++ index) % n;
            }
            else {
                //如果index下标的值为flase,则只需index++;
                index = (++ index) % n; //[0, n-1]
            }


        }
        //找活着的那个;
        for (int i=0; i<n; ++i) {
            if(array[i]) {
                return i;
            }
        }
        return -1;
    }
    public static void main(String[] args) {

        System.out.println(CyclicGame(4, 3));
    }

这里只是个人的学习总结。有什么问题欢迎提意见。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值