Skip to content

Commit 1dced8e

Browse files
committed
better State representation in queens
1 parent eff9fac commit 1dced8e

File tree

1 file changed

+14
-27
lines changed

1 file changed

+14
-27
lines changed

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

Lines changed: 14 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -16,29 +16,17 @@ class QueensSuite extends FunSuite {
1616
import scala.concurrent.ExecutionContext.Implicits.global
1717
given Gopher[Future] = SharedGopherAPI.apply[Future]()
1818

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) {
2622

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+
}
3227

33-
3428
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)
4230

4331
}
4432

@@ -47,32 +35,31 @@ class QueensSuite extends FunSuite {
4735
def putQueen(state:State): ReadChannel[Future,State] =
4836
val ch = makeChannel[State]()
4937
async[Future] {
50-
val i = state.queens.length
38+
val i = state.length
5139
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) }
5341
ch.write(state.put(i,j))
5442
ch.close()
5543
}
5644
ch
5745

5846
def solutions(state: State): ReadChannel[Future,State] =
5947
async[[X] =>> ReadChannel[Future,X]] {
60-
if(state.queens.size < N) then
48+
if(state.size < N) then
6149
val nextState = await(putQueen(state))
6250
await(solutions(nextState))
6351
else
6452
state
6553
}
6654

67-
val emptyState = State(Set.empty, Set.empty, Set.empty, Set.empty, Vector.empty)
6855

6956
test("two first solution for 8 queens problem") {
7057
async[Future] {
71-
val r = solutions(emptyState).take(2)
58+
val r = solutions(Vector.empty).take(2)
7259
assert(!r.isEmpty)
73-
println(r.map(_.queens))
60+
println(r)
7461
}
7562
}
7663

7764

78-
}
65+
}

0 commit comments

Comments
 (0)