while coding recursive solution for towers of hanoi, my code works for 1, 2 and 3 discs but not after that. not able to figure out what am i doing wrong.
package recursion;
import java.util.List;
import org.springframework.util.Assert;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
public class Hanoi {
private static List<Integer> reference = Lists.newArrayList(4, 3, 2, 1);
private static List<Integer> aList = Lists.newArrayList(reference);
private static List<Integer> bList = Lists.newArrayListWithCapacity(aList.size() - 1);
private static List<Integer> cList = Lists.newArrayListWithCapacity(aList.size());
public static void main(String[] args) {
hanoi(aList, bList, cList);
System.out.println(cList);
Assert.isTrue(cList.equals(reference));
Assert.isTrue(aList.size() == 0);
Assert.isTrue(bList.size() == 0);
System.out.println("done");
}
private static void hanoi(List<Integer> aList, List<Integer> bList, List<Integer> cList) {
if (aList.size() == 1) {
cList.add(aList.remove(0));
return;
}
hanoi(aList.subList(1, aList.size()), cList, bList);
print();
hanoi(aList.subList(0, 1), null, cList);
print();
hanoi(bList, aList, cList);
print();
System.out.println("=======================================");
}
private static void print() {
System.out.println(aList);
System.out.println(bList);
System.out.println(cList);
Assert.isTrue(Ordering.natural().reverse().isOrdered(aList));
Assert.isTrue(Ordering.natural().reverse().isOrdered(bList));
Assert.isTrue(Ordering.natural().reverse().isOrdered(cList));
System.out.println("******************************************");
}
}
Your algorithm is based on the assumption that towers of hanoi always shifts all slices except one in the first (and last) step.
This is assumption is wrong. Subproblems shift smaller towers.
Add a param size to your hanoi-method. All three steps have to be adjusted: