写完了

This commit is contained in:
Kagura 2024-06-15 22:48:50 +08:00
parent 2e63f21b26
commit d7a81cffe5
3 changed files with 96 additions and 2 deletions

6
LL1/.idea/vcs.xml Normal file
View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>

View file

@ -1,4 +1,7 @@
class analyzeTable {
import java.util.*
import kotlin.collections.ArrayDeque
class AnalyzeTable {
var V_n = mutableListOf<String>()
var V_t = mutableListOf<String>("#")
@ -197,6 +200,8 @@ class analyzeTable {
var copy = string
var no_vt_now = true
while (copy.isNotEmpty() && no_vt_now) {
val backup = copy
V_t.forEach {
if (copy.startsWith(it)){
parsedString.add(it)
@ -220,7 +225,76 @@ class analyzeTable {
}
}
copy = copy.substring(startVn.length)
if (backup == copy){
throw RuntimeException("""
出现了未知符号${copy[0]}
at: $copy
^---------This
""".trimIndent())
}
}
return parsedString
}
public fun analyze(input: String,transform: (String) -> String) : List<String> {
val analyzeDeque = ArrayDeque<String>()
analyzeDeque.addLast("#")
analyzeDeque.addLast(start)
val inputDeque = ArrayDeque<String>()
inputDeque.addLast("#")
val result = mutableListOf<String>()
splitToVn(transform(input),false).forEach {
inputDeque.addLast(it)
}
while (true) {
// 在这个时候保存栈
result.add(
"${result.size+1}: "
.padEnd(4)
+
"${analyzeDeque
.toString()
.replace("[","")
.replace("]","")
.replace(",","")
.replace(" ","")
.padEnd(10)}\t" +
"${inputDeque.reversed()
.toString()
.replace("[","")
.replace("]","")
.replace(",","")
.replace(" ","")
.padStart(6)}\t"
)
// 栈顶一样删除
if (analyzeDeque.last() == inputDeque.last()) {
analyzeDeque.removeLast()
inputDeque.removeLast()
if (analyzeDeque.isEmpty() && inputDeque.isEmpty()){
result[result.size - 1] = "${result[result.size - 1]}成功"
return result
}
continue
}
// 动作
val action = table["${analyzeDeque.removeLast()},${inputDeque.last()}"]
if (action == null) {
result[result.size - 1] = "${result[result.size - 1]}错误"
return result
} else {
splitToVn(items[action].split("->")[1], false).reversed().forEach {
analyzeDeque.addLast(it)
}
result[result.size - 1] = "${result[result.size - 1]}${items[action]}"
}
}
}
}

View file

@ -1,5 +1,5 @@
fun main() {
val analyzeTable = analyzeTable()
val analyzeTable = AnalyzeTable()
println("输入的文法:")
for (i in analyzeTable.items.indices) {
println("$i: ${analyzeTable.items[i]}")
@ -8,4 +8,18 @@ fun main() {
analyzeTable.table.forEach {
println("${it.key}: ${analyzeTable.items[it.value]}")
}
println("分析过程:")
analyzeTable.analyze("98+99+80"){
it.replace("\\d+".toRegex(),"i")
}.forEach {
println(it)
}
analyzeTable.analyze("(106-80(*95)"){
it.replace("\\d+".toRegex(),"i")
}.forEach {
println(it)
}
}