File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1- const displayBoard = ( board ) => {
2- console . log ( "\n" ) ;
3- for ( const row of board ) {
4- console . log ( ...row )
5- }
6- }
7-
81class NQueen {
92 constructor ( size ) {
103 this . board = new Array ( size ) . fill ( '.' ) . map ( ( ) => new Array ( size ) . fill ( '.' ) )
114 this . size = size
12- this . solutions = [ ]
5+ this . solutionCount = 0
136 }
147
158 isValid ( [ row , col ] ) {
@@ -33,17 +26,18 @@ class NQueen {
3326 return true
3427 }
3528
36- placeQueen ( row , col ) {
29+ placeQueen ( row , col ) {
3730 this . board [ row ] [ col ] = 'Q'
3831 }
3932
40- removeQueen ( row , col ) {
41- this . board [ row ] [ col ] = '.' ;
33+ removeQueen ( row , col ) {
34+ this . board [ row ] [ col ] = '.'
4235 }
4336
4437 solve ( col = 0 ) {
4538 if ( col >= this . size ) {
46- this . solutions . push ( JSON . parse ( JSON . stringify ( this . board ) ) ) ;
39+ this . printBoard ( )
40+ this . solutionCount ++
4741 return true
4842 }
4943
@@ -57,19 +51,13 @@ class NQueen {
5751
5852 return false
5953 }
60- }
6154
62- function main ( ) {
63- const nQueen = new NQueen ( 4 )
64- displayBoard ( nQueen . board )
65- nQueen . solve ( )
66-
67- console . log ( "Number of solutions:" , nQueen . solutions . length ) ;
68- nQueen . solutions . forEach ( ( solution ) => {
69- displayBoard ( solution )
70- } ) ;
55+ printBoard ( ) {
56+ console . log ( '\n' )
57+ for ( const row of this . board ) {
58+ console . log ( ...row )
59+ }
60+ }
7161}
7262
73- // main()
74-
75- export { NQueen } ;
63+ export { NQueen }
Load diff This file was deleted.
Original file line number Diff line number Diff line change 1+ import { NQueen } from '../NQueen'
2+
3+ describe ( 'NQueen' , ( ) => {
4+ it ( 'should return 2 solutions for 4x4 size board' , ( ) => {
5+ const nQueen = new NQueen ( 4 )
6+ nQueen . solve ( )
7+ expect ( nQueen . solutionCount ) . toEqual ( 2 )
8+ } )
9+
10+ it ( 'should return 92 solutions for 8x8 size board' , ( ) => {
11+ const nQueen = new NQueen ( 8 )
12+ nQueen . solve ( )
13+ expect ( nQueen . solutionCount ) . toEqual ( 92 )
14+ } )
15+ } )
You can’t perform that action at this time.
0 commit comments