/** * Solve the Instant Insanity puzzle. Four cubes have sides colored red, green, * blue, and white. The object is to arrange them into a tower so that each side * of the tower has exactly one of each color. * * This version prunes by testing each placement for validity before going on. * It also tests "buried" colors to make sure that a solution is still possible. * * Based on an earlier C++ version that Scot Drysdale wrote for CS 15. * * @author Scot Drysdale */ public class Insane3 { private static int numPlacements; private static int validityTests; /** * Performs the backtracking by placing cube number "cubeNum" in all possible * positions. This version rejects a placement if it conflicts with earlier * cube placements or has too many of a given color buried (appearing on * the top or bottom face of a placed cube). * @param cubes the stack of cubes to place in all positions * @param cubeNo the cube currently being placed */ public static void PlaceCube(CubeTower cubes, int cubeNo) { numPlacements++; // Count another cube placed if (cubeNo > CubeTower.NUMCUBES) { // All cubes placed? System.out.println(cubes); } else { for (int tips = 1; tips <= 3; tips++) { // For each of three top-bottom pairs cubes.bury(cubeNo); // Bury top and bottom colors of current cube if (cubes.buriedOK()) { if (cubeNo == 1) { // First cube has 3 non-symetric positions validityTests++; if(cubes.isValid(cubeNo)) PlaceCube(cubes, cubeNo+1); } else { // Other cubes have 24 possible positions for (int rot = 1; rot <= 4; rot++) { // For each of 4 rotation positions validityTests++; if(cubes.isValid(cubeNo)) PlaceCube(cubes, cubeNo+1); cubes.rotate(cubeNo); } cubes.flip(cubeNo); for (int rot = 1; rot <= 4; rot++) { // For each of 4 rotation positions validityTests++; if(cubes.isValid(cubeNo)) PlaceCube(cubes, cubeNo+1); cubes.rotate(cubeNo); } cubes.flip(cubeNo); // Get back to original position } } cubes.unbury(cubeNo); // Different set of faces will be buried cubes.rotate(cubeNo); cubes.tip(cubeNo); // Get a different top-bottom pair } } } public static void main(String [] args) { CubeTower cubes = new CubeTower(); // Stack of cubes to place numPlacements = 0; // Count nodes examined validityTests = 0; // Count validity tests made PlaceCube(cubes, 1); System.out.println("Number of cube placements: " + numPlacements + "\nNumber of validity tests: " + validityTests); } }