fork download
  1. /*Sergey Kondrashov http://i...content-available-to-author-only...a.ru/
  2.   Case Study 3
  3.   JavaScript version of the exercise as alternative solution the task from the book Timothy A. Budd, An Introduction to
  4. Object-Oriented Programming http://w...content-available-to-author-only...e.edu/~budd/Books/oopintro2e/
  5.   Задача о Восьми ферзях. Вариация решения на JavaScript задачи, предложенной Т. Баддом в книге "" http://w...content-available-to-author-only...e.edu/~budd/Books/oopintro2e/Russian.html
  6. */
  7.  
  8. function Queen(column, QueenObj){
  9. // поля данных
  10. this.row = 1;
  11. this.column = column;
  12. this.neighbor = QueenObj;
  13. // поиск и печать решения
  14. this.findSolution = function(){
  15. // проверить позицию, не атакуют ли соседи
  16. while(this.neighbor && this.neighbor.canAttack(this.row, this.column)){
  17. if(!this.advance())
  18. return false;
  19. }
  20. //решение найдено
  21. return true;
  22.  
  23. }
  24. this.advance = function(){
  25. if(this.row < 8){
  26. this.row++;
  27. return this.findSolution();
  28. }
  29. if(this.neighbor && !this.neighbor.advance())
  30. return false;
  31. this.row = 1;
  32. return this.findSolution();
  33. }
  34. this.print = function(){
  35. if(this.neighbor)
  36. this.neighbor.print();
  37. print("column == " + this.column + " row == " + this.row);
  38. }
  39. // внутренний метод
  40. this.canAttack = function(testRow, testColumn){
  41. // проверка горизонтали
  42. if(this.row == testRow)
  43. return true;
  44. // проверка диагоналей
  45. var columnDifference = testColumn - this.column
  46. if((this.row + columnDifference == testRow) || (this.row - columnDifference == testRow))
  47. return true;
  48. // попробовать соседа
  49. return (this.neighbor && this.neighbor.canAttack(testRow, testColumn));
  50. }
  51. return this;
  52. }
  53.  
  54. function main(){
  55. var lastQueen = 0;
  56. for (var i = 1; i <= 8; i++){
  57. lastQueen = new Queen(i, lastQueen);
  58. if(!lastQueen.findSolution())
  59. print("no solution");
  60. }
  61. lastQueen.print();
  62. }
  63. main();
Success #stdin #stdout 0.01s 5088KB
stdin
Standard input is empty
stdout
column == 1 row == 1
column == 2 row == 5
column == 3 row == 8
column == 4 row == 6
column == 5 row == 3
column == 6 row == 7
column == 7 row == 2
column == 8 row == 4