Java uses a queue to solve the problem of Joseph

Joseph problem:

      Legend in the Jewish War parks in the first century, Jewish Joseph was well-known historian of the first century AD. After the Roman occupation Qiaotapate, 39 Jews and Joseph and his friends hid in a cave, 39 Jews decided'd rather die than not to be captured by the enemy, and decided a suicide spread through the ages of 41 individual row in a circle, the first personal Countin, report every third person that the person must commit suicide, and then reported that the number again by the next person, until everyone committed suicide so far. But Joseph and his friends did not want to comply with this agreement, Joseph wanted his friend to pretend to comply, he will arrange with his friends in the first _ and _ one position, then escaped death in this game, you know arrange Well the first of several?

Queue implementation:

package org.codewy.algorithm.josephusproblem;

import java.util.LinkedList;
import java.util.Queue;

public class JosephusProblem {
    
    public static void main(String[] args) {
        Queue<Integer> persons = new LinkedList();

        for (int i = 1; i < 42; i++) {
            persons.add(i);
        }

        int count = 0;

        while (persons.size() > 2) {
            count++;
            Integer person = persons.poll();
            if (count % 3 == 0) {
                System.out.println("die: " + person);
            } else {
                persons.add(person);
            }
        }

        System.out.println("alive: " + persons);
    }

}

Output:

 

Guess you like

Origin www.cnblogs.com/codewy/p/11779197.html