Add OS X/Swift and Python implementations of the Eight Queens problem

This commit is contained in:
Donald Burr 2015-05-28 20:31:49 -07:00
parent 6130affabf
commit e609b323a2
5 changed files with 452 additions and 0 deletions

View file

@ -0,0 +1,19 @@
//
// Queen.swift
// EightQueens
//
// Created by Donald Burr on 5/27/15.
// Copyright (c) 2015 Donald Burr. All rights reserved.
//
import Foundation
class Queen {
var row: Int
var column: Int
init(forRow: Int) {
row = forRow
column = 0
}
}

View file

@ -0,0 +1,80 @@
//
// main.swift
// EightQueens
//
// Created by Donald Burr on 5/27/15.
// Copyright (c) 2015 Donald Burr. All rights reserved.
//
import Foundation
var solutionsFound = 0
var positionsChecked = 0
// create 8 queen objects, place them one per row
let myQueens = map(0...7) { Queen(forRow: $0) }
func isSafe(currentRow: Int, currentColumn: Int) -> Bool {
positionsChecked++
// iterate over all queens in previous rows
for previousRow in 0..<currentRow {
// check vertical: are we trying to place in the same column as a previously placed queen?
if myQueens[previousRow].column == currentColumn {
return false
}
// check diagonal
let differenceInRows = currentRow - previousRow
let differenceInColumns = currentColumn - myQueens[previousRow].column
if (differenceInRows == differenceInColumns || differenceInRows == -differenceInColumns) {
return false
}
}
// compared all previous queens, no conflict
myQueens[currentRow].column = currentColumn
return true
}
func moveQueenAcrossRow(row: Int) {
for column in 0...7 {
// move queen column by column, checking if it's safe
if isSafe(row, column) {
// if we just placed the 8th queen, we have a result!
if row == 7 {
solutionsFound++
printAnswer()
} else {
// recursive call - now move the queen to the NEXT row
moveQueenAcrossRow(row+1)
}
}
}
}
func printAnswer() {
println("SOLUTION #\(solutionsFound)")
println()
// go backwards to print from top down
for currentRow in reverse(0...7) {
// print row number (using chess numbering)
print(currentRow+1)
for currentColumn in 0...7 {
if (myQueens[currentRow].column == currentColumn) {
print(" Q ")
} else {
print(" . ")
}
}
println()
}
println(" A B C D E F G H ")
println()
}
// start by trying to move queen across row 0
moveQueenAcrossRow(0)
// that's it
println("POSITIONS CHECKED: \(positionsChecked)")