@@ -16,29 +16,17 @@ class QueensSuite extends FunSuite {
16
16
import scala .concurrent .ExecutionContext .Implicits .global
17
17
given Gopher [Future ] = SharedGopherAPI .apply[Future ]()
18
18
19
- case class State (
20
- busyRows: Set [Int ],
21
- busyColumns: Set [Int ],
22
- busyLRDiagonals: Set [Int ],
23
- busyRLDiagonals: Set [Int ],
24
- queens : Vector [(Int ,Int )]
25
- ) {
19
+ type State = Vector [(Int ,Int )]
20
+
21
+ extension(queens: State ) {
26
22
27
- def isBusy (i: Int , j: Int ): Boolean =
28
- busyRows.contains(i) ||
29
- busyColumns.contains(j) ||
30
- busyLRDiagonals.contains(i- j) ||
31
- busyRLDiagonals.contains(i+ j)
23
+ def isUnderAttack (i: Int , j: Int ): Boolean =
24
+ queens.exists{ (qi,qj) =>
25
+ qi == i || qj == j || i- j == qi- qj || i+ j == qi+ qj
26
+ }
32
27
33
-
34
28
def put (i: Int , j: Int ): State =
35
- copy( busyRows = busyRows + i,
36
- busyColumns = busyColumns + j,
37
- busyLRDiagonals = busyLRDiagonals + (i- j),
38
- busyRLDiagonals = busyRLDiagonals + (i+ j),
39
- queens = queens :+ (i,j)
40
- )
41
-
29
+ queens :+ (i,j)
42
30
43
31
}
44
32
@@ -47,32 +35,31 @@ class QueensSuite extends FunSuite {
47
35
def putQueen (state: State ): ReadChannel [Future ,State ] =
48
36
val ch = makeChannel[State ]()
49
37
async[Future ] {
50
- val i = state.queens. length
38
+ val i = state.length
51
39
if i < N then
52
- for { j <- 0 until N if ! state.isBusy (i,j) }
40
+ for { j <- 0 until N if ! state.isUnderAttack (i,j) }
53
41
ch.write(state.put(i,j))
54
42
ch.close()
55
43
}
56
44
ch
57
45
58
46
def solutions (state : State ): ReadChannel [Future ,State ] =
59
47
async[[X ] =>> ReadChannel [Future ,X ]] {
60
- if (state.queens. size < N ) then
48
+ if (state.size < N ) then
61
49
val nextState = await(putQueen(state))
62
50
await(solutions(nextState))
63
51
else
64
52
state
65
53
}
66
54
67
- val emptyState = State (Set .empty, Set .empty, Set .empty, Set .empty, Vector .empty)
68
55
69
56
test(" two first solution for 8 queens problem" ) {
70
57
async[Future ] {
71
- val r = solutions(emptyState ).take(2 )
58
+ val r = solutions(Vector .empty ).take(2 )
72
59
assert(! r.isEmpty)
73
- println(r.map(_.queens) )
60
+ println(r)
74
61
}
75
62
}
76
63
77
64
78
- }
65
+ }
0 commit comments