Skip to content

Instantly share code, notes, and snippets.

@nealhu
Created July 5, 2014 06:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nealhu/f8d39eba344cfe8bda81 to your computer and use it in GitHub Desktop.
Save nealhu/f8d39eba344cfe8bda81 to your computer and use it in GitHub Desktop.
CC_3_4
// Cracking the Coding Interview
// 3.4 In the classic problem of the Towers of Hanoi, you have 3 towers and Ndisks of different sizes which can slide onto any tower.The puzzle starts with disks sorted in ascending order of size from top to bottom (i.e., each disk sits on top of an even larger one). You have the following constraints:
// (1) Only one disk can be moved at a time.
// (2) A disk is slid off the top of one tower onto the next tower.
// (3) A disk can only be placed on top of a larger disk.
// Write a program to move the disks from the first tower to the last using stacks.
import java.util.Stack;
class HanoiTowers {
public static void move(int num, Stack<Integer> ori, Stack<Integer> dest, Stack<Integer> buf) {
if (num == 0) {
return;
} else if (num == 1) {
dest.push(ori.pop());
} else {
move(num-1, ori, buf, dest);
move(1, ori, dest, buf);
move(num-1, buf, dest, ori);
}
}
public static void main(String[] args) {
Stack<Integer> s0 = new Stack<Integer>();
Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>();
s0.push(1);
move(1, s0, s1, s2);
assert areEqual(s1, new int[]{1}) && s0.empty() && s2.empty();
s0 = new Stack<Integer>();
s1 = new Stack<Integer>();
s2 = new Stack<Integer>();
for(int i = 9; i >= 1; i--) {
s0.push(i);
}
move(9, s0, s1, s2);
assert areEqual(s1, new int[]{9, 8, 7, 6, 5, 4, 3, 2, 1}) && s0.empty() && s2.empty();
System.out.println("Tests Passed");
}
public static boolean areEqual(Stack<Integer> s, int[] arr) {
if (s.size() != arr.length) return false;
for(int i = 0; i < arr.length; i++) {
if (arr[i] != s.pop()) return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment