I am working on an assignment for class:
Josephus problem. In the Josephus problem from antiquity, N people are in dire straits and agree to the following strategy to reduce the population. They arrange themselves in a circle (at positions numbered from 0 to N???1) and proceed around the circle, eliminating every Mth person until only one person is left. Legend has it that Josephus figured out where to sit to avoid being eliminated. Write a Queue client Josephus.java that takes M and N from the command line and prints out the order in which people are eliminated (and thus would show Josephus where to sit in the circle).
My code is as follows :
package josephus;
import java.util.Queue;
public class Josephus {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]),
m = Integer.parseInt(args[1]);
Queue<Integer> q = new Queue<Integer>();
for (int i = 0; i < n; i++)
q.enqueue(new Integer(i));
int k = 0;
while (!q.isEmpty())
{
int x = q.dequeue();
if (++k % m == 0)
StdOut.print(x + " ");
else
q.enqueue(x);
}
StdOut.println();
} }
When I run it in NetBeans it gives me errors stating that:
Queue is abstract; cannot be instantiated
enqueue: Cannot find symbol
dequeue: Cannot find symbol
StdOut: Cannot find symbol
I thought that by importing the java.util.Queue would make the Queue work and for the StdOut I did download a stdlib.jar to add to the projects library which inculdes StdOut and I thought that would work.
If there is a problem with my code or anything else I need to do, I would really appreciate the help. Also, for reference and to see where I got the stdlib.jar, here is the link for the textbooks website from where this problem comes from : http://algs4.cs.princeton.edu/13stacks/ (The Josephus problem is #37 under the "Creative problems section" towards the end.
Queue
is an interface and cannot be directly instantiated in Java. You must provide a concrete implementation class, such as ArrayDeque
.
Queue<Integer> q = new ArrayDeque<Integer>();
The queue methods enqueue
and dequeue
are named differently -- offer
and poll
, respectively. E.g.:
q.offer(i);
and
int x = q.poll();
StdOut
is not a class in Java; use System.out
, e.g.:
System.out.print(x + " ");