Thursday, 25 August 2016

Chapter 7 Exercise 22, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.


***7.22 (Game: Eight Queens) The classic Eight Queens puzzle is to place eight queens on a chessboard such that no two queens can attack each other (i.e., no two queens are on the same row, same column, or same diagonal). There are many possible solutions. Write a program that displays one such solution. A sample output is shown below:


|Q| | | | | | | |
| | | | |Q| | | |
| | | | | | | |Q|
| | | | | |Q| | |
| | |Q| | | | | |
| | | | | | |Q| |
| |Q| | | | | | |
| | | |Q| | | | | 




public class ProgrammingEx7_22 {
 public static void main(String[] args) {
  int chessboardSize = 8;
  int[] chessboard = new int[chessboardSize];
  for (int i = 0; i < 077777777; i++) {
   int tmp = i;
   for (int j = chessboardSize - 1; j >= 0; j--, tmp /= chessboardSize)
    chessboard[j] = tmp % chessboardSize;
   if (!isHorizonalFine(chessboard))
    continue;   
   if (!isDiagonalFine(chessboard))
    continue;   
   printChessboard(chessboard);
   break;
  }
 }
 
 public static boolean isHorizonalFine(int[] chessboard) {
  boolean[] numbers = new boolean[chessboard.length];
  for (int i = 0; i < chessboard.length; i++)
   numbers[chessboard[i]] = true;
  for (int i = 0; i < numbers.length; i++)
   if (!numbers[i])
    return false;
  return true; 
 }
 
 public static boolean isDiagonalFine(int[] chessboard) {
  for (int i = 0; i < chessboard.length; i++) {
   for (int j = i + 1; j < chessboard.length; j++) {
    if (chessboard[j] - chessboard[i] == j - i) 
     return false;
    if (chessboard[i] - chessboard[j] == j - i) 
     return false;
   }
  }
  return true; 
 }
 
 public static void printChessboard(int[] chessboard) {
  for (int i = 0; i < chessboard.length; i++) {
   for (int j = 0; j < chessboard.length; j++)
    System.out.print(chessboard[i] == j ? "|Q" : "| ");
   System.out.println("|");
  }
  System.out.println();
 }
}

3 comments :

  1. hello again
    i guess your answer is wrong!!!

    ReplyDelete
  2. @zakaria hashi thank you i will have a look in a while and if found any issues will report back with correction.

    ReplyDelete
  3. @zakaria hashi thank you yes the solution had problem but have fixed it now. Thank you once again for contributing.

    ReplyDelete