A number n of Names you have saved in a text file should be

A number n of Names you have saved in a text file should be read into an arrays of strings. This number should be entered by the user and it must be greater than or equals to three (validate this entry).

Arrange those n Names in a line in alphabetical ascending order, in order to transfer them from this location A to location C Using location C as an intermediate of temporary location while obeying two simple rules:

1. Only one name can be moved at a time

2. A larger (alphabetically) name can never go in front of a smaller one.

Write a recursive Java code that will print each move made in transferring the n (arranged) Names from location A to C, and the number of moves needed for the transfer. Make sure your algorithm will use the smallest number of moves. Don’t use stacks or queues or anything not discussed over the previous chapters (basically only use arrays and recursion).

The output should look like this --

Solution

public class TowerOfHanoiUsingStacks { public static int N; /* Creating Stack array */ public static Stack[] tower = new Stack[4]; public static void main(String[] args) { Scanner scan = new Scanner(System.in); tower[1] = new Stack(); tower[2] = new Stack(); tower[3] = new Stack(); /* Accepting number of disks */ System.out.println(\"Enter n : \"); int num = scan.nextInt(); N = num; if(N < 3) { System.out.println(\"Must be greater than or equal to 3\"); System.exit(0); } String line; List list = new ArrayList(); try ( InputStream fis = new FileInputStream(\"the_file_name\"); InputStreamReader isr = new InputStreamReader(fis, Charset.forName(\"UTF-8\")); BufferedReader br = new BufferedReader(isr); ) { for(int i=0; i 0; d--) tower[1].push(d); display(); move(n, 1, 2, 3); } /* Recursive Function to move disks */ public static void move(int n, int a, int b, int c) { if (n > 0) { move(n-1, a, c, b); int d = tower[a].pop(); tower[c].push(d); display(); move(n-1, b, a, c); } } /* Function to display */ public static void display() { System.out.println(\" A | B | C \"); System.out.println(\"---------------\"); for(int i = N - 1; i >= 0; i--) { String d1 = \" \", d2 = \" \", d3 = \" \"; try { d1 = String.valueOf(tower[1].get(i)); } catch (Exception e){ } try { d2 = String.valueOf(tower[2].get(i)); } catch(Exception e){ } try { d3 = String.valueOf(tower[3].get(i)); } catch (Exception e){ } System.out.println(\" \"+list.get(d1)+\" | \"+list.get(d2)+\" | \"+list.get(d3)+\" \"); } System.out.println(\"\ \"); } }
A number n of Names you have saved in a text file should be read into an arrays of strings. This number should be entered by the user and it must be greater tha

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site