fork download
  1. /*Sergey Kondrashov http://i...content-available-to-author-only...a.ru/
  2.   Case Study 4
  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.  
  9. function Queen(column_, QueenObj){
  10. // поля данных
  11. this.row = 1;
  12. this.column = column_;
  13. this.neighbor = QueenObj;
  14. return this;
  15. }
  16. // поиск и печать решения
  17. Queen.prototype.findSolution = function(){
  18. // проверить позицию, не атакуют ли соседи
  19. while(this.neighbor != 0 && this.neighbor.canAttack(this.row, this.column)){
  20. if(!this.advance())
  21. return false;
  22. }
  23. //решение найдено
  24. return true;
  25.  
  26. }
  27.  
  28. Queen.prototype.advance = function(){
  29. if(this.row <= 8 ){
  30. this.row++;
  31. return this.findSolution();
  32. }
  33. this.row = 1;
  34. if(this.neighbor != 0 && !this.neighbor.advance())
  35. return false;
  36.  
  37. return this.findSolution();
  38. }
  39. Queen.prototype.print = function(){
  40. if(this.neighbor != 0)
  41. this.neighbor.print();
  42. print("column == " + this.column + " row == " + this.row);
  43. }
  44.  
  45. // внутренний метод
  46. Queen.prototype.canAttack = function(testRow, testColumn){
  47. // проверка горизонтали
  48. if(this.row == testRow)
  49. return true;
  50. // проверка диагоналей
  51. var columnDifference = testColumn - this.column;
  52. if(((this.row + columnDifference) == testRow) || ((this.row - columnDifference) == testRow))
  53. return true;
  54. // попробовать соседа
  55. if(this.neighbor != 0)
  56. return this.neighbor.canAttack(testRow, testColumn);
  57. else
  58. return false;
  59. }
  60.  
  61. function main(){
  62. var lastQueen = 0;
  63. for (var i = 1; i <= 8; i++){
  64. lastQueen = new Queen(i, lastQueen);
  65. var check = lastQueen.findSolution();
  66. if(!check)
  67. print("no solution")
  68. }
  69. lastQueen.print();
  70. }
  71. main();
Success #stdin #stdout 0s 5108KB
stdin
Standard input is empty
stdout
column == 1 row == 1
column == 2 row == 3
column == 3 row == 6
column == 4 row == 8
column == 5 row == 2
column == 6 row == 4
column == 7 row == 9
column == 8 row == 7