用数组来模拟约瑟夫环

public class Count3Quit {

    public static void main(String[] args) {
        boolean[] array = new boolean[500];
        
        //给每个位置设置为true
        for(int i = 0; i < array.length; i++) {
            array[i] = true;
        }
        
        int len = array.length;    //当前在圈内的个数
        int count = 0;    //计数器,每次报到3时,kill掉
        int index = 0;    //用于遍历所有人
        
        while(len > 1) {
            if(array[index] == true) {    //当此人在圈内时
                count++;    
                if(count == 3) {    //每隔三个人,标记为false,意思有一个人被kill掉了
                    count = 0;
                    array[index] = false;
                    len--;
                }
            }
            index++;
            if(index == array.length) {    //如果数到最后一个人,在从第一个人数
                index = 0;
            }
        }
        
        //输出最后圈中或者的人的编号
        for(int i = 0; i < array.length ;i++) {
            if(array[i] == true) {
                System.out.println("最后活着的人的编号是:  " + i);
            }
        }

    }
    

}

输出结果是:

最后活着的人的编号是:  435

猜你喜欢

转载自www.cnblogs.com/pangxiaoshuai/p/10808259.html