Skip to content

Commit 76403f2

Browse files
committed
optimization of 8 queens problen
1 parent ff2d110 commit 76403f2

File tree

1 file changed

+18
-15
lines changed

1 file changed

+18
-15
lines changed

shared/src/test/scala/gopher/monads/Queens.scala

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -21,48 +21,51 @@ class QueensSuite extends FunSuite {
2121
busyColumns:Set[Int],
2222
busyLRDiagonals:Set[Int],
2323
busyRLDiagonals:Set[Int],
24-
queens: Set[(Int,Int)]
24+
queens: Vector[(Int,Int)]
2525
);
2626

2727
val N = 8
2828

2929
def putQueen(state:State): ReadChannel[Future,State] =
3030
val ch = makeChannel[State]()
3131
async[Future] {
32-
for{
33-
i <- 0 until N if !state.busyRows.contains(i)
34-
j <- 0 until N if !state.busyColumns.contains(j) &&
32+
val i = state.queens.length
33+
if i < N then
34+
for{
35+
j <- 0 until N if !state.busyColumns.contains(j) &&
3536
!state.busyLRDiagonals.contains(i-j) &&
3637
!state.busyRLDiagonals.contains(i+j)
37-
} {
38-
val newPos = (i,j)
39-
val nState = state.copy( busyRows = state.busyRows + i,
38+
} {
39+
val newPos = (i,j)
40+
val nState = state.copy( busyRows = state.busyRows + i,
4041
busyColumns = state.busyColumns + j,
4142
busyLRDiagonals = state.busyLRDiagonals + (i-j),
4243
busyRLDiagonals = state.busyRLDiagonals + (i+j),
43-
queens = state.queens + newPos )
44-
ch.write(nState)
45-
}
44+
queens = state.queens :+ newPos )
45+
ch.write(nState)
46+
}
4647
ch.close()
4748
}
4849
ch
4950

5051
def solutions(state: State): ReadChannel[Future,State] =
5152
async[[X] =>> ReadChannel[Future,X]] {
52-
if(state.queens.size < 8) then
53+
if(state.queens.size < N) then
54+
//println("state:"+state.queens)
5355
val nextState = await(putQueen(state))
56+
//println("next-state:"+state.queens)
5457
await(solutions(nextState))
5558
else
5659
state
5760
}
5861

59-
val emptyState = State(Set.empty, Set.empty, Set.empty, Set.empty, Set.empty)
62+
val emptyState = State(Set.empty, Set.empty, Set.empty, Set.empty, Vector.empty)
6063

61-
test("first solution for 8 queens problem") {
64+
test("two first solution for 8 queens problem") {
6265
async[Future] {
63-
val r = solutions(emptyState).take(1)
66+
val r = solutions(emptyState).take(2)
6467
assert(!r.isEmpty)
65-
println(r.head.queens)
68+
println(r.map(_.queens))
6669
}
6770
}
6871

0 commit comments

Comments
 (0)