1.3.37 Josephus问题

解法:

public static Queue Josephus(int num, int integer){
    Queue survivors = new Queue<>();
    Queue deads = new Queue<>();
    for(int i = 0; i < num; i++){
        survivors.enqueue(i);
    }
    
    for(int i = 1; survivors.size() != 0; i++){
        int person = survivors.dequeue();
        if((i%integer) == 0){
            deads.enqueue(person);
        }else{
            survivors.enqueue(person);
        }
    }
    
    return deads;
}

测试:

public static void main(String[] args) {
    System.out.println(Josephus(7, 2)); 
}

结果:

1 3 5 0 4 2 6 

你可能感兴趣的:(1.3.37 Josephus问题)