当前位置: 代码迷 >> 综合 >> 丢手帕问题(Josephus问题)
  详细解决方案

丢手帕问题(Josephus问题)

热度:67   发布时间:2024-01-18 23:49:04.0

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

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();
    }
  相关解决方案