/*Sergey Kondrashov http://i...content-available-to-author-only...a.ru/
Case Study 4
JavaScript version of the exercise as alternative solution the task from the book Timothy A. Budd, An Introduction to
Object-Oriented Programming http://w...content-available-to-author-only...e.edu/~budd/Books/oopintro2e/
Задача о Восьми ферзях. Вариация решения на JavaScript задачи, предложенной Т. Баддом в книге "" http://w...content-available-to-author-only...e.edu/~budd/Books/oopintro2e/Russian.html
*/
function Queen(column_, QueenObj){
// поля данных
this.row = 1;
this.column = column_;
this.neighbor = QueenObj;
return this;
}
// поиск и печать решения
Queen.prototype.findSolution = function(){
// проверить позицию, не атакуют ли соседи
while(this.neighbor != 0 && this.neighbor.canAttack(this.row, this.column)){
if(!this.advance())
return false;
}
//решение найдено
return true;
}
Queen.prototype.advance = function(){
if(this.row <= 8 ){
this.row++;
return this.findSolution();
}
this.row = 1;
if(this.neighbor != 0 && !this.neighbor.advance())
return false;
return this.findSolution();
}
Queen.prototype.print = function(){
if(this.neighbor != 0)
this.neighbor.print();
print("column == " + this.column + " row == " + this.row);
}
// внутренний метод
Queen.prototype.canAttack = function(testRow, testColumn){
// проверка горизонтали
if(this.row == testRow)
return true;
// проверка диагоналей
var columnDifference = testColumn - this.column;
if(((this.row + columnDifference) == testRow) || ((this.row - columnDifference) == testRow))
return true;
// попробовать соседа
if(this.neighbor != 0)
return this.neighbor.canAttack(testRow, testColumn);
else
return false;
}
function main(){
var lastQueen = 0;
for (var i = 1; i <= 8; i++){
lastQueen = new Queen(i, lastQueen);
var check = lastQueen.findSolution();
if(!check)
print("no solution")
}
lastQueen.print();
}
main();