Results 1 to 3 of 3

Thread: Hanoi- HELP

  1. #1
    xajaxworldx is offline Member
    Join Date
    May 2011
    Posts
    5
    Rep Power
    0

    Unhappy Hanoi- HELP


    Here's what professor says and i need your help. and scroll down, I made code so far and been struggle for a long time. THanks.

    Code Background
    Collection Classes in Package java.util
    The java.util package defines generic container classes that play the role of predefined data structures. In commercial code,
    programmers will likely use predefined packaged data structures rather than “reinventing the wheel” and writing their own.
    But programmers who know how to create their own basic data structures like smart arrays, linked lists, hash tables, and
    binary search trees will have great insight to guide them in correctly using the predefined versions.
    The most basic collection class is the ArrayList. This class implements the List interface with an array as its backing store,
    providing a general “smart array” object that automatically expands its capacity as more data items are added. This is a good
    starting point for any application that needs a general container for general data items. The Vector class is almost identical to
    ArrayList, except that objects of type Vector are automatically synchronized for multithreaded programs, while ArrayList
    objects are not. If multithreading support is not needed, ArrayList incurs slightly less overhead than Vector.
    The collections classes all define parameterized types. They also work only with data items of reference types. It is not
    possible to insert primitive values into a collection object directly. But because of wrapper classes and
    autoboxing/autounboxing, the behavior is increasingly hidden, and most programs can be written as if primitives were
    supported directly.
    ArrayList<Integer> list; // okay
    ArrayList<int> list2; // not okay
    More info on correct usage of parameterized types is provided below.
    Collections are defined as a combination of interfaces (ADTs) and classes that implement those interfaces. Here are some
    representative definitions from java.util:
    Interfaces: Collection, List, Map, Queue, Set
    Concrete Class Categories: array, link, hash table, tree, enumeration
    Concrete Classes: ArrayList, LinkedList, HashMap, HashTable, EnumMap, EnumSet, TreeMap, TreeSet,
    Stack, Vector
    Common Methods: add(), get(), set(), remove(), clear(), contains(), size(), equals(), toString(), toArray()
    The behavior of most of the common methods is self-explanatory. The get() method retrieves a copy of the object reference
    at a specific index, without removing it. The set() method replaces the existing reference at a specific index with a new
    reference. There are two versions of the add() method. The version with one param grows the collection at the high index
    end. The version with two params inserts at the specified index. It is an error to insert into a non-existent position.
    Other collection classes may provide additional customized methods in addition to this common set. For example, the Stack
    class defines push(), pop() and other traditionally named stack methods.
    See the following example of using an ArrayList to hold and manage a collection of int values.
    ArrayList Example
    ArrayList<Integer> list = new ArrayList<Integer>();
    System.out.println("add(int) tests");
    for (int i=1; i<=10; i++) {
    list.add(2*i+3); System.out.println(list);
    }
    System.out.println("size = " + list.size()); System.out.println();
    System.out.println("remove(int) tests");
    list.remove(5); System.out.println(list);
    list.remove(3); System.out.println(list);
    list.remove(4); System.out.println(list);
    System.out.println("size = " + list.size()); System.out.println();
    System.out.println("set(int,int) tests");
    list.set(0,25); System.out.println(list);
    list.set(4,27); System.out.println(list);
    System.out.println("size = " + list.size()); System.out.println();
    System.out.println("add(int,int) tests");
    list.add(1,29); System.out.println(list);
    list.add(6,31); System.out.println(list);
    System.out.println("size = " + list.size()); System.out.println();
    // note: cannot call set or add on index positions
    // that don't already exist
    // list.add(50,33); // generates IndexOutOfBoundsException
    Output
    add(int) tests
    [5]
    [5, 7]
    [5, 7, 9]
    [5, 7, 9, 11]
    [5, 7, 9, 11, 13]
    [5, 7, 9, 11, 13, 15]
    [5, 7, 9, 11, 13, 15, 17]
    [5, 7, 9, 11, 13, 15, 17, 19]
    [5, 7, 9, 11, 13, 15, 17, 19, 21]
    [5, 7, 9, 11, 13, 15, 17, 19, 21, 23]
    size = 10
    remove(int) tests
    [5, 7, 9, 11, 13, 17, 19, 21, 23]
    [5, 7, 9, 13, 17, 19, 21, 23]
    [5, 7, 9, 13, 19, 21, 23]
    size = 7
    set(int,int) tests
    [25, 7, 9, 13, 19, 21, 23]
    [25, 7, 9, 13, 27, 21, 23]
    size = 7
    add(int,int) tests
    [25, 29, 7, 9, 13, 27, 21, 23]
    [25, 29, 7, 9, 13, 27, 31, 21, 23]
    size = 9
    Boxing and Unboxing Primitive Types
    The collections classes are defined to contain only object references. It is not possible to insert primitive values into
    collections directly. But since each primitive type has a corresponding wrapper class to represent it, primitives can easily be
    wrapped or “boxed” with a wrapper class object. Before Java generics, it was common to write code like the following:
    Vector v = new Vector();
    Integer y = new Integer(3); // 1 “boxing”
    v.add(y);

    Integer w = (Integer) v.get(0);
    int z = w.intValue(); // 2 “unboxing”
    The lines in bold are examples of boxing and unboxing the result. Boxing on line 1 causes the primitive value 3 to be boxed
    as Integer object y. Unboxing on line 2 causes the int value z to be extracted from the boxed value w.
    Autobox and Autounbox
    To further simplify the use of primitives with collections, the Java compiler will now automatically provide the box and
    unbox functions for the programmer. Combined with parameterized types, the previous program can now be written in a
    much more simple and type-safe style as follows:
    Vector<Integer> v = new Vector<Integer>();
    v.add(3);

    int z = v.get(0);
    Note that the 2nd version generates no compiler warning messages.
    Generics and Type Safety
    Now that Java supports generics, programmers are strongly encouraged to use them. To maintain backward compatibility
    with older code, the compiler will allow parameterized types to be used without a type parameter, but the compiler issues a
    warning that the code is not type safe. Code that is not type safe is at risk of generating ClassCastException at runtime.
    Here’s an example that illustrates the problem.
    “Old” Type-Unsafe Style
    Vector v = new Vector();
    v.add(3);
    int x = (Integer) v.get(0);
    System.out.println(x);
    The parameterized type “Vector” without an actual type parameter is called a raw type. Creating objects from raw types is
    allowed but discouraged. The biggest problem with this example is the type cast that is required on line 3. The generic
    version of the get() method is defined to return a reference of type Object. Without the typecast, the code will not compile.
    With the typecast, the code compiles but generates a type safety warning.
    The reason for the warning is that there is no assurance at runtime that reference returned by get() really is an Integer. Since
    the Vector is a raw type, any object of any type can be added to it.
    v.add(“abc”);
    v.add(new Double(3.14159));
    v.add(new Scanner(System.in));

    When fetching stored references from this Vector later, complex runtime type checking will be required.
    This problem is easily solved by introducing a type parameter, the recommended style.
    “New” Type Safe Style
    Vector<Integer> v = new Vector<Integer>();
    v.add(3); // okay
    v.add(“abc”); // compiler error
    int x = v.get(0); // no typecast required
    Attempts to add the wrong type of data are caught by the compiler, and using get() to retrieve data no longer requires a
    typecast.
    Professional-level programming using Java Generics is challenging and requires much practice. There are many complex
    and subtle rules. Here are just a few that are relevant to this project.
    Arrays of Parameterized Type Objects Not Supported
    Suppose a program creates several integer stacks.
    Stack<Integer> stk0 = new Stack<Integer>();
    Stack<Integer> stk1 = new Stack<Integer>();
    Stack<Integer> stk2 = new Stack<Integer>();
    Suppose we wish to store the stacks into an “array of Stacks”:
    Stack<Integer> []stks = new Stack<Integer>[3]; // NOT ALLOWED
    stks[0] = stk0;
    stks[1] = stk1;
    stks[2] = stk2;
    It is a subtle rule regarding correct usage of parameterized types that arrays of parameterized type objects are not normally
    allowed. Instead, they can be added to another collection object.
    ArrayList<Stack<Integer>> stks = new ArrayList<Stack<Integer>>();
    stks.add(stk0);
    stks.add(stk1);
    stks.add(stk2);
    Code Skeleton For Project
    import java.util.*;
    public class Hanoi {
    private int n; // number of disks
    private int movecount; // current number of moves
    // collection of 3 stacks (towers)
    private ArrayList<Stack<Integer>> stks;
    // constructor to create the three stacks (towers) and initialize
    // them into their initial state for a given value of n
    //
    // tower 0: n n-1 n-2 … 3 2 1
    // tower 1: empty
    // tower 2: empty
    public Hanoi(int ni) { }
    // show()
    // show content of tower “which”
    // content can be displayed with System.out.print(stk)
    public void show(int which) { }
    // showall()
    // show content of all stacks
    public void showall() { }
    // init state of towers 0, 1, and 2
    private void init() { }
    // move disk from tower “from” to tower “to”
    private void move(int from, int to) { }
    // private recursive solve
    // this method operates recursively on number of disks n
    // and the id of each of the 3 towers a (src), b (dst), and c (spare)
    // note that for n==1, the move() function is called
    private void solve(int n, int a, int b, int c) {
    if (n==1) move(a,b);
    else {
    solve(n-1,a,c,b);
    solve(1,a,b,c);
    solve(n-1,c,b,a);
    }
    }
    // top-level non-recursive solve
    // this method simply initiates the solve by identifying the
    // initial role of towers 0, 1, and 2
    public void solve() {
    solve(n,0,1,2);
    }
    }
    class Driver {
    public static void main(String[] args) {
    Hanoi h = new Hanoi(Integer.parseInt(args[0]));
    h.showall();
    h.solve();
    }
    }
    The call to solve() starts the solution. Internally, it initiates the series of recursive calls to generate the moves. Since this a
    simulation, however, the method does not simply print out the name of the move, but updates the state of the appropriate
    stack. You will probably want the option of having the intermediate states of the solution to print out to the display as well,
    at least for small values of n.




    --------------------------------------------------------------------------

    Java Code:
    import java.util.*;
    
    
    public class Hanoi 
    {
    	private int n; // number of disks
    	private int movecount; // current number of moves
    
    	// collection of 3 stacks (towers)
    	private ArrayList<Stack<Integer>> stks;
    //	private void solve();
    	
    	
    	
    	
    	
     
    		
    	// constructor to create the three stacks (towers) and initialize
    	// them into their initial state for a given value of n
    	//
    	// tower 0: n n-1 n-2 … 3 2 1
    	// tower 1: empty
    	// tower 2: empty
    	
    	
    	
    
    	public Hanoi(int ni) 
    	{
    		int product = 1;
    		for (int i=2; i<=n; i++) product *= i;
    			return product;
    			
    		System.out.print(stks);
    	
    	 }
    
    	// show()
    	// show content of tower “which”
    	// content can be displayed with System.out.print(stk)
    		
    	
    	public void show(int which) 
    	{ 
    		if (which==n) return n;
    			else return which;
    	
    		system.out.println(show);
    	}
    	// showall()
    	// show content of all stacks
    
    
    
    	public void showall() 
    	{
    		if (n <=0)
    			movecount++;
    		else
    		{
    			return empty ;
    		}	
    			
    	 }
    	// init state of towers 0, 1, and 2
    	private void init() 
    	{ 
    		solve(0,1,2);
    	}
    	// move disk from tower “from” to tower “to”
    	private void move(int from, int to) 
    	{ 
    		movecount++;
    		if(n<=10)
    		{
    			System.out.print("Move from " + from + "to " + to + ". ");
    		if (movecount%4 == 0)
    		{
    			System.out.println();
    		}
    		}
    		else
    		{
    			System.out.println("Move from " + from + " to " + to + ". ");
    			if (movecount%4==0)
    			{
    				System.out.println();
    			}
    		}
    		}
    		
    		
    	}
    		
    	
    	
    	// private recursive solve
    	// this method operates recursively on number of disks n
    	// and the id of each of the 3 towers a (src), b (dst), and c (spare)
    	// note that for n==1, the move() function is called
    	private void solve(int n, int a, int b, int c) 
    	{
    		if (n==1) 
    		
    			move(a,b);
    
    		else 
    		{
    			solve(n-1,a,c,b);
    			solve(1,a,b,c);
    			solve(n-1,c,b,a);
    		}
    	}
    	
    /*	// ADDED by MYSELF:::
    	private ArrayList<Stack<Integer>>stks()
    	{
    	
    		move(a,b);
    			int value = stks.get(a).pop();
    			stks.get(b).push(value);
    			System.out.println(s.charAt(3));
    			
    			ArrayList<Stack<Integer>> stks = new ArrayList<Stack<Integer>>();
    		stks.add(stk0);
    		stks.add(stk1);
    		stks.add(stk2);
    		System.out.println(stks);
    	}
    */
    	// top-level non-recursive solve
    	// this method simply initiates the solve by identifying the
    	// initial role of towers 0, 1, and 2
    	public void solve() 
    	{
    		/* if (n==1) return (a+b+ " ");
    			else return solve(n-1,a,c,b) + solve(1,a,b,c) +
    				solve(n-1,c,b,a);
    		*/
    		solve(n, 0, 1, 2);
    
    	}
    }
    }

    Thanks.
    Last edited by xajaxworldx; 05-06-2011 at 05:21 AM.

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,197
    Rep Power
    19

    Default

    Recommended reading: How to ask questions the smart way

    Use code tags to post codes -- [code]CODE[/code] will display as
    Java Code:
    CODE
    db

  3. #3
    xajaxworldx is offline Member
    Join Date
    May 2011
    Posts
    5
    Rep Power
    0

    Default thanks

    Ah, now I got it! thanks for give me a tip how to put the code stuff. There you go. thanks.

Similar Threads

  1. Towers of Hanoi
    By myst in forum New To Java
    Replies: 1
    Last Post: 07-11-2010, 06:24 PM
  2. Replies: 5
    Last Post: 04-28-2010, 04:42 PM
  3. Towers of Hanoi using Producer/Consumer Pattern
    By dooey in forum New To Java
    Replies: 0
    Last Post: 09-08-2009, 12:45 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •