Since you know Java well, but C++ no so well, this assignment is to convert a Java program into a C++ program.
(For another comparison of C++ and Java, see the sieve program in Java and compare it to the sieve program in C++ in the text.)
Here's the program in Java. We'll discuss it in detail in class.
public class QueenDemo { public static void main (String [] args) { System.out.println("\nThe eight-queens problem is to find all possible"); System.out.println("positions of eight queens so that none attack any other."); System.out.println("Here are the solutions to the 8-queens problem\n"); // Create the first queen and the rest of the row of 8 queens Queen first = new Queen(8,1,null); // Try placing the first queen, then the rest in possible ranks in // their columns first.place(); } }
public class Queen { private int size; // dimension of the board private int file; // the fixed file for this queen private int rank; // the variable rank for this queen private Queen left, right; // the neighboring queens /* Create yourself on a board of the specified size, in the specified file, and all the queens to your right, so that each queen knows its immediate neighbors */ public Queen(int sizeIn, int fileIn, Queen leftIn) { size = sizeIn; file = fileIn; left = leftIn; if (size < file) right = new Queen(size, file+1, this); } /* Try placing yourself in all possible ranks */ public void place() { for (rank=1; rank<=size; ++rank) if (file==1 || !left.attack(file,rank)) if (file1) left.print(); System.out.print(" "+this); if (file==size) System.out.println(); } /* Do you or any queens to your left attack this square? */ private boolean attack(int f, int r) { return inSight(file,rank,f,r) || (file>1 && left.attack(f,r)); } /* Are the two squares in sight of each other? That is, are they on the same rank or in the same diagonal? It's assumed they're in different files */ private static boolean inSight(int f1, int r1, int f2, int r2) { return r1==r2 || Math.abs(f1-f2)==Math.abs(r1-r2); } public String toString() { return "["+rank+","+file+"]"; } }
Here are the first few lines of output when you run the program, and the last line.
$ java QueenDemo The eight-queens problem is to find all possible positions of eight queens so that none attack any other. Here are the solutions to the 8-queens problem [1,1] [5,2] [8,3] [6,4] [3,5] [7,6] [2,7] [4,8] [1,1] [6,2] [8,3] [3,4] [7,5] [4,6] [2,7] [5,8] [1,1] [7,2] [4,3] [6,4] [8,5] [2,6] [5,7] [3,8] [1,1] [7,2] [5,3] [8,4] [2,5] [4,6] [6,7] [3,8] [2,1] [4,2] [6,3] [8,4] [3,5] [1,6] [7,7] [5,8] [2,1] [5,2] [7,3] [1,4] [3,5] [8,6] [6,7] [4,8] [2,1] [5,2] [7,3] [4,4] [1,5] [8,6] [6,7] [3,8] [2,1] [6,2] [1,3] [7,4] [4,5] [8,6] [3,7] [5,8] ... [8,1] [4,2] [1,3] [3,4] [6,5] [2,6] [7,7] [5,8] $
Back to the course page.