Skip to content

Instantly share code, notes, and snippets.

@richard1122
Last active July 8, 2020 14:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richard1122/2ecf5b5c9d1bedaa50c9e937305d8fdf to your computer and use it in GitHub Desktop.
Save richard1122/2ecf5b5c9d1bedaa50c9e937305d8fdf to your computer and use it in GitHub Desktop.
String construction
import java.io.File
import java.io.FileInputStream
import java.util.*
// Unique index for each Vertex
var currentIndex = 0
class Vertex(private val index: Int = ++currentIndex) {
var terminate = false
val edges = mutableMapOf<Char, Vertex>()
override fun equals(other: Any?): Boolean = other is Vertex && other.index == index
override fun hashCode(): Int = index
}
fun appendVertex(root: Vertex, template: String) {
var current: Vertex = root
template.forEach { char ->
val next = current.edges[char]
if (next == null) {
current.edges[char] = Vertex()
}
current = current.edges[char]!!
}
current.terminate = true
}
fun match(input: String, root: Vertex): Boolean {
val finalStates = input.fold(setOf(root), { states, char ->
val translationStates = mutableSetOf<Vertex>() // Next state set
states.forEach {
val nextState = it.edges[char]
if (nextState != null) {
// Can move to next state
translationStates.add(nextState)
// If current state is a terminate state (end of a template string),
// add root state.
// But current state is still available for next transition
if (nextState.terminate) translationStates.add(root)
}
// Else skip current state
}
translationStates
})
return finalStates.any { it.terminate }
}
fun main(args: Array<String>) {
val scanner = Scanner(FileInputStream(File(args[0])))
val input = scanner.nextLine()
val root = Vertex()
root.terminate = true
scanner.nextLine().split(' ').forEach { appendVertex(root, it) }
println(match(input, root))
}
@richard1122
Copy link
Author

input

01010101010001101
01 10 010 101 100

output true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment