Last active
August 29, 2015 14:15
-
-
Save neojou/0a22d40ae0ddc42a42f5 to your computer and use it in GitHub Desktop.
Hanoi program written in Java.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* To change this license header, choose License Headers in Project Properties. | |
* To change this template file, choose Tools | Templates | |
* and open the template in the editor. | |
*/ | |
package nj.app; | |
import java.util.*; | |
import static java.lang.System.in; | |
import static java.lang.System.out; | |
/** | |
* | |
* @author neojou | |
*/ | |
public class Hanoi { | |
private int num = 0; | |
class Disk { | |
int id = 0; | |
Disk(int id) { | |
if ( id > 0 ) | |
this.id = id; | |
} | |
public int getID() { | |
return this.id; | |
} | |
public String toString() { | |
return String.format("Disk(%d)", this.id); | |
} | |
public int compareTo(Object arg0) throws ClassCastException{ | |
Disk obj=(Disk) arg0; | |
if(this.id > obj.getID()){return 1;} | |
else if(this.id < obj.getID()){return -1;} | |
else{return 0;} | |
} | |
} | |
class Pole extends ArrayList | |
{ | |
String name = ""; | |
Pole(String name) { | |
this.name = name; | |
} | |
String getName() { | |
return this.name; | |
} | |
} | |
private Pole pole1 = new Pole("A"); | |
private Pole pole2 = new Pole("B"); | |
private Pole pole3 = new Pole("C"); | |
Hanoi(int num) { | |
if (num > 0 ) { | |
this.num = num; | |
/// create disks and all put at pole1 | |
for (int i=0; i< num; i++) { | |
Disk d = new Disk(i+1); | |
out.print("set disk: "); | |
out.println(d); | |
pole1.add(d); | |
} | |
} | |
} | |
void show_status(Pole p) { | |
out.printf("%s: %s %n", p.getName(), p); | |
} | |
void show_status() { | |
show_status(pole1); | |
show_status(pole2); | |
show_status(pole3); | |
} | |
void move() | |
{ | |
move_disks(pole1, pole2, pole3, this.num); | |
} | |
void move_disks(Pole p1, Pole p2, Pole p3, int num) { | |
if ( num == 1 ) { | |
move_disk(p1, p2); | |
} | |
else { | |
move_disks(p1, p3, p2, num-1); | |
move_disk(p1, p2); | |
move_disks(p3, p2, p1, num-1); | |
} | |
} | |
void move_disk(Pole p1, Pole p2) { | |
Disk topP1 = (Disk)p1.remove(0); | |
out.printf("Move %s from %s to %s %n", topP1, p1.getName(), p2.getName() ); | |
p2.add(0, topP1); | |
} | |
/** | |
* @param args the command line arguments | |
*/ | |
public static void main(String[] args) { | |
// TODO code application logic here | |
Scanner console = new Scanner(in); | |
out.print("Input Hanoi tower number : "); | |
int disk_num = console.nextInt(); | |
out.printf("%n number = [%d] %n", disk_num); | |
Hanoi hanoi = new Hanoi(disk_num); | |
hanoi.show_status(); | |
hanoi.move(); | |
hanoi.show_status(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment