javaarraysqueueboundsjosephus

Array out of bounds exception, Josephus


I can't seem to figure out why I keep getting this error! It's my first time dealing with Queues. I'm sure the solution is simple and I'm probably missing something basic. Any guidance/help is greatly appreciated:

import java.util.LinkedList;
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 LinkedList<Integer>();
    for (int i = 0; i < n; i++)
        q.remove(new Integer(i));

    int k = 0;
    while (!q.isEmpty())
    {
        int x = q.remove();

        if (++k % m == 0)
            System.out.print(x + " ");
        else
            q.remove(x);

    System.out.println(x + " ");
    }
    }
}

The original prompt for this code is as follows: 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 them- selves 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 that takes N and M 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).


Solution

  • You are calling your program the wrong way... if you use command line, you must provide parameters :

    java Josephus 5 6
    

    Otherwise if you use Eclipse (for example), you must go to Run as, Run configurations, and add some arguments in the Program arguments field. You can also replace your first line by manually typed values :

    int n = 10, m = 5;
    

    I ran it with random sets of (m,n) values and it ran without any error (however, it didn't print anything).