File tree Expand file tree Collapse file tree 3 files changed +28
-41
lines changed Expand file tree Collapse file tree 3 files changed +28
-41
lines changed 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
-
8
1
class NQueen {
9
2
constructor ( size ) {
10
3
this . board = new Array ( size ) . fill ( '.' ) . map ( ( ) => new Array ( size ) . fill ( '.' ) )
11
4
this . size = size
12
- this . solutions = [ ]
5
+ this . solutionCount = 0
13
6
}
14
7
15
8
isValid ( [ row , col ] ) {
@@ -33,17 +26,18 @@ class NQueen {
33
26
return true
34
27
}
35
28
36
- placeQueen ( row , col ) {
29
+ placeQueen ( row , col ) {
37
30
this . board [ row ] [ col ] = 'Q'
38
31
}
39
32
40
- removeQueen ( row , col ) {
41
- this . board [ row ] [ col ] = '.' ;
33
+ removeQueen ( row , col ) {
34
+ this . board [ row ] [ col ] = '.'
42
35
}
43
36
44
37
solve ( col = 0 ) {
45
38
if ( col >= this . size ) {
46
- this . solutions . push ( JSON . parse ( JSON . stringify ( this . board ) ) ) ;
39
+ this . printBoard ( )
40
+ this . solutionCount ++
47
41
return true
48
42
}
49
43
@@ -57,19 +51,13 @@ class NQueen {
57
51
58
52
return false
59
53
}
60
- }
61
54
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
+ }
71
61
}
72
62
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