丢手帕问题(Josephus问题)

来源:互联网 发布:淘宝48分店铺解封 编辑:程序博客网 时间:2024/04/28 13:04

为了实现有限个元素的不断循环使用

public class Josephus {

    public static void main(String[] args) {
        int M = Integer.parseInt(args[0]);
        int N = Integer.parseInt(args[1]);

        // initialize the queue
        Queue<Integer> q = new Queue<Integer>();
        for (int i = 0; i < N; i++)
            q.enqueue(i);

        while (!q.isEmpty()) {
            for (int i = 0; i < M-1; i++)
                q.enqueue(q.dequeue());
            StdOut.print(q.dequeue() + " ");
        } 
        StdOut.println();
    }
0 0