The Josephus Problem

Chapter: The Josephus Problem

Read about it in Wikipedia. Or play with this applet until you understand the problem.

        
             
            Your browser is ignoring the <APPLET> tag!      
        

It's like some of the games children play to choose who is "it" except it's much more deadly. You can pick how many soldiers you want to participate. Then pick a number "n". The applet will commence to kill every n'th living soldier until only one remains.

Here is my code for Josephus. Study it and make sure it makes sense to you. Probably you have never seen the "invokeLater" code:

                 SwingUtilities.invokeLater(new Runnable() {
                         public void run() {
                             doIt();
                         }
                     });

You may remember from CSci 53 how easy it is to run threads (or ActiveObjects as they were known then) using the objectdraw library. objectdraw shielded you from some of the grim reality related to running threaded programs in Java. What we really want to do here is start the animation by running the method public void doIt. And, indeed, you could replace the 5 lines of code above by one simple call to doIt() and your code would probably run just fine. But after the first run of the program, strange things would happen because the same thread that is maintaining the GUI is also modifying it. This can cause nullPointerExceptions and things that go bump in the night. And the Java documentation does warn you that animations such as the doIt thread should not be running in the same thread that is dispatching AWT events. This invokeLater(.. code is a way I have found to be reliable in launching threads. For more technical details you can begin by looking at the documentation for SwingUtilities where you should read about the invokeLater method.


Exercise 2

Make a project with my Josephus.java and your finished CircularList from Exercise 1. It should work! BlueJ is an easy environment to do this exercise in because it will automatically make the .html files you need in order to run the applet.


rhyspj@gwu.edu