-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshaney.kt
69 lines (60 loc) · 1.79 KB
/
shaney.kt
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
// Based on the program presented in the "Design and Implementation" chapter
// of The Practice of Programming (Kernighan and Pike, Addison-Wesley 1999).
// See also Computer Recreations, Scientific American 260, 122 - 125 (1989).
import java.io.File
import kotlin.system.exitProcess
class Prefix() {
var content = arrayOf<String>("", "")
override fun toString(): String {
return content.joinToString(" ")
}
fun shift(word: String) {
content[0] = content[1]
content[1] = word
}
}
class Chain() {
val chain = mutableMapOf<String, ArrayList<String>>()
fun build(text: String) {
val words = text.split(" ", "\n")
val p = Prefix()
var key: String
for (w in words) {
key = p.toString()
chain.getOrPut(key) { arrayListOf() }.add(w)
p.shift(w)
}
}
fun generate(length: Int): String {
val p = Prefix()
val words = arrayListOf<String>()
var choices: ArrayList<String>
var next: String
for (i in 0 until length) {
if (p.toString() in chain.keys) {
choices = chain[p.toString()]!!
if (choices.size == 0) break
} else break
next = choices.random()
words.add(next)
p.shift(next)
}
return words.joinToString(" ")
}
}
fun main(args: Array<String>) {
if (args.size != 2) {
println("Mark V. Shaney")
print("Synopsis shaney <num words to generate> <input>.txt")
exitProcess(2)
}
val file = File(args[1])
if (!file.exists()) {
println("File ${file.name} does not exist")
exitProcess(2)
}
val c = Chain()
c.build(file.readText())
val text = c.generate(args[0].toInt())
println(text)
}