2009-08-11 1 views
2

Ich wollte Leistungsvergleiche für verschiedene Ansätze zur Lösung des N-Königinnen-Problems bewerten. Hauptsächlich auf AI-Metaheuristiken basierende Algorithmen wie Simulated Annealing, Tabu-Suche und genetischer Algorithmus etc. im Vergleich zu exakten Methoden (wie Backtracking). Gibt es einen Code für das Studium? Eine Menge von realen Optimierungsproblemen wie es betrachten kooperative Schemata zwischen genauen Methoden und Metaheuristiken.Vergleich der algorithmischen Ansätze zum N-Königinnen-Problem

Antwort

0

Ich musste einen N-Queens Solver in Java für eine Klasse vor ein paar Jahren in der Schule schreiben. Ich bin nicht sicher, welche Art von Quellcode Sie suchen, aber wenn es irgendeine Hilfe wäre hier ist der Code aus diesem Programm. Es ist in keiner Weise wirklich optimiert, nur ein ziemlich einfacher rekursiver Algorithmus. Ich habe dies mein erstes Semester am College geschrieben, also entschuldige die Anfängerfehler :-) Ich habe die meisten Blockkommentare rausgenommen, aber hoffentlich kannst du es mit denen, die ich hinterlassen habe, verstehen. Wenn du einen professionellen Quellcode willst Vielleicht eine Google-Suche durchführen? Ich weiß, dass Wikipedia einige anständige Artikel und Pseudocode hatte. Hoffe das hilft!

import java.util.Scanner; 
public class QueensSolver 
{ 
public static void main(String args[]) 
{ 
    System.out.println("Please enter the size of the chessboard: "); 
    Scanner stdin = new Scanner(System.in); 
    int sizeOfBoard = stdin.nextInt(); 
    //Create the board to the given size. 
    char[][] board = new char[sizeOfBoard][sizeOfBoard]; 

    //fill board with hyphens 
    for(int row=0; row<sizeOfBoard; row++) 
    { 
     for(int col=0; col<sizeOfBoard; col++) 
     { 
      board[row][col] = '-'; 
     } 
    } 

    //Call the method which attempts to solve the problem 
    if(solve(sizeOfBoard, board, 0)) 
    { //if true, we know that the board array contains a solution 
     printBoard(sizeOfBoard, board); 
    } 
    else 
    { //if false, we know that no solutions exist on this size of board 
     System.out.println("No solutions are possible with this board size."); 
    } 
} 

public static boolean solve(int sizeOfBoard, char[][] board, int row) 
{ 
    //If all rows have been filled, we have a solution 
    if(row>=sizeOfBoard) 
    { 
     return true; 
    } 
    //For each column(space) on the given row 
    for(int col=0; col<sizeOfBoard; col++) 
    { 
     //If placing a queen in this column(space) does not cause a conflict 
     if(!checkConflict(sizeOfBoard, board, row, col)) 
     { 
      //place a queen here 
      board[row][col]='Q'; 
      //then call this same function on the next row 
      boolean success = solve(sizeOfBoard, board, row+1); 
      //if every function in this recursive path returns true 
      if(success) 
      { 
       //then we return true also 
       return true; 
      } 
      //If there is no possible solution with this queen placement, 
      //then we replace the queen with an empty and attempt 
      //to place a queen in the next column(space). 
      else 
      { 
       board[row][col]='-'; 
      } 
     } 
    } 
    return false; 
} 

public static boolean checkConflict(int sizeOfBoard, char[][] board, int rowCheck, int colCheck) 
{ 
    //Check for queens placed directly above this position 
    for(int row = rowCheck-1; row>=0; row--) 
    { 
     if(board[row][colCheck]=='Q') 
     { 
      return true; 
     } 
    } 

    //Check for queens placed on the diagonal 
    //above and to the right of this position 
    int col = colCheck+1; 
    for(int row = rowCheck-1; row>=0; row--) 
    { 

     if(col>=sizeOfBoard) 
     { 
      break; 
     } 
     if(board[row][col]=='Q') 
     { 
      return true; 
     } 
     col++; 
    } 

    //Check for queens placed on the diagonal 
    //above and to the left of this position 
    col = colCheck-1; 
    for(int row = rowCheck-1; row>=0; row--) 
    { 

     if(col<0) 
     { 
      break; 
     } 

     if(board[row][col]=='Q') 
     { 
      return true; 
     } 
     col--; 
    } 
    //We know that no conflicts are caused by this position, so return false 
    return false; 
} 

public static void printBoard(int sizeOfBoard, char[][] board) 
{ 
    for(int row=0; row<sizeOfBoard; row++) 
    { 
     for(int col=0; col<sizeOfBoard; col++) 
     { 
      System.out.print(board[row][col]); 
     } 
     System.out.print("\n"); 
    } 
} 
} 
0

Ich weiß nicht wirklich Ihre Frage bekommen (haben Sie die Theorie des Algorithmus wissen? Sie wollen also den Code sehen?), Aber ich bin bereit, den Code zu teilen, die ich aus der Natur angepasst. Es ist Python und es ist ziemlich cool. Ich habe es geändert, um Iteratoren zu verwenden, und auf wundersame Weise funktioniert es immer noch.

# I can't really claim much credit for this implementation. 
# I found this on the web and I converted it to use python generators. 
# Adapted from: 
#  http://en.wikibooks.org/wiki/Algorithm_implementation/Miscellaneous/N-Queens 

def queensproblem(solution, rows, columns): 
    def add_one_queen(new_row, columns, solution): 
     for new_column in range(columns): 
      if not conflict(new_row, new_column, solution): 
       yield new_column 

    def conflict(new_row, new_column, solution): 
     return any(solution[row]  == new_column or 
        solution[row] + row == new_column + new_row or 
        solution[row] - row == new_column - new_row 
        for row in range(new_row)) 

    if len(solution) == rows: 
     yield solution 
    else : 
     for row in range(len(solution), rows): 
      for col in add_one_queen(row, columns, solution): 
       for x in queensproblem(solution + [col], rows, columns): 
        yield x 
      else: 
       break 

if __name__ == '__main__': 
    for i,solution in enumerate(queensproblem([], 8, 8)): 
     print i, solution 
0

Ein schöner Ansatz besteht in der Datei test/test_generators.py der Python-Standardbibliothek. Überprüfen Sie die Queens-Klasse. Wenn Sie Python nicht auf Ihrem Computer installiert haben, können Sie die Datei online durchsuchen here.

0

Dies ist nicht die schnellste mögliche Implementierung des Schemas, aber es ist ziemlich prägnant. Ich habe es mir selbst ausgedacht, aber ich bezweifle, dass es einzigartig ist. Es ist in PLT Scheme, daher müssen einige Funktionsnamen geändert werden, damit sie in R6RS ausgeführt werden. Die Liste der Lösungen und jeder Lösung ist mit Widersprüchen aufgebaut, also sind sie umgekehrt. Die Umkehrungen und Maps am Ende reorder alles und fügen Sie Zeilen zu den Lösungen für eine hübsche Ausgabe. Die meisten Sprachen haben eine Art Funktion fold, siehe:
http://en.wikipedia.org/wiki/Fold_%28higher-order_function%29

#lang scheme/base 
(define (N-Queens N) 

    (define (attacks? delta-row column solution) 
    (and (not (null? solution)) 
     (or (= delta-row (abs (- column (car solution)))) 
      (attacks? (add1 delta-row) column (cdr solution))))) 

    (define (next-queen safe-columns solution solutions) 
    (if (null? safe-columns) 
     (cons solution solutions) 
     (let move-queen ((columns safe-columns) (new-solutions solutions)) 
      (if (null? columns) new-solutions 
       (move-queen 
       (cdr columns) 
       (if (attacks? 1 (car columns) solution) new-solutions 
        (next-queen (remq (car columns) safe-columns) 
           (cons (car columns) solution) 
           new-solutions))))))) 

    (unless (exact-positive-integer? N) 
    (raise-type-error 'N-Queens "exact-positive-integer" N)) 
    (let ((rows (build-list N (λ (row) (add1 row))))) 
    (reverse (map (λ (columns) (map cons rows (reverse columns))) 
        (next-queen (build-list N (λ (i) (add1 i))) null null)))))