-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAlgo.scala
78 lines (61 loc) · 2.37 KB
/
Algo.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import scala.collection.parallel.mutable
/**
* Created by me on 2/29/2016.
*/
class Algo(level: Int) {
private val FULL_SOURCE: String = "0123456789abcdefghijklmnopqrstuvwxyz"
val SOURCE_LEN = level + 9
val SECRET_LEN = level + 3
val SOURCE = FULL_SOURCE.substring(0, SOURCE_LEN)
private val secret: String = generateSecret()
private var gameOver: Boolean = false
def getSecret(): String = { gameOver = true; secret }
private def generateSecret(): String = {
def generateSecret0(s: String, result: String): String =
if (result.length == SECRET_LEN) {
result
} else {
val i = scala.util.Random.nextInt(s.length)
val c = s.charAt(i)
generateSecret0(s.substring(0, i) + s.substring(i + 1, s.length), result + c)
}
generateSecret0(SOURCE, "")
}
val SECRET_POOL_SIZE = 500 * 1000
var possibleSecrets: collection.mutable.Seq[String] = collection.mutable.Seq()
var pendingPrefix: collection.mutable.Set[String] = collection.mutable.SortedSet[String]()
var pendingSuffix: collection.mutable.Map[String, Seq[String]] = collection.mutable.Map()
// initial prefix & suffix
pendingPrefix += ""
pendingSuffix += "" -> collection.mutable.Seq(SOURCE)
private def filter(previousResults: Seq[Result]): Seq[String] = {
possibleSecrets.filter(s => Result.of(s, secret).isMatched())
}
def iteratePending(): Unit = {
if (pendingPrefix.isEmpty) return
pendingPrefix.foreach(pre => {
if (possibleSecrets.size > SECRET_POOL_SIZE) return
println(pre)
val suf: Seq[String] = pendingSuffix(pre)
pendingPrefix -= pre
pendingSuffix -= pre
if (pre.length < SECRET_LEN - 1) {
suf.foreach(s => {
for (i <- 0 to s.length - 1) {
val newPre = pre + s.charAt(i)
pendingPrefix += newPre
val newSuf: Seq[String] = pendingSuffix.getOrElse(newPre, Seq[String]()) :+ (s.substring(0, i) + s.substring(i + 1, s.length))
pendingSuffix.put(newPre, newSuf)
}
})
}
else if (pre.length == SECRET_LEN - 1) {
// suf.foreach(s => {
// s.map(c => pre + c).foreach(possibleSecrets :+ _)
// })
possibleSecrets = possibleSecrets ++ suf.map(s => s.map(c => pre + c)).fold[Seq[String]](Seq())((s1, s2) => s1 ++ s2)
println("Adding new set to possible secret...")
}
})
}
}