Skip to content

Instantly share code, notes, and snippets.

@JunJaBoy
Created April 27, 2024 04:55
Show Gist options
  • Save JunJaBoy/a0d27a879278f806bfc28d5627af1a18 to your computer and use it in GitHub Desktop.
Save JunJaBoy/a0d27a879278f806bfc28d5627af1a18 to your computer and use it in GitHub Desktop.
HackerRank/Algorithm/SimpleTextEditor kotlin
import java.util.*
class TextEditor(initialValue: String = "") {
private val operationHistory = Stack<String>().apply { push(initialValue) }
val value: String
get() = operationHistory.peek()
fun append(text: String) {
operationHistory.push(operationHistory.peek() + text)
}
fun delete(count: Int) {
operationHistory.push(value.dropLast(count))
}
fun print(number: Int) {
println(value[number - 1])
}
fun undo() {
operationHistory.pop()
}
}
const val OP_APPEND = 1
const val OP_DELETE = 2
const val OP_PRINT = 3
const val OP_UNDO = 4
fun editText(
operations: LinkedList<Pair<Int, String?>>,
scanner: Scanner,
): String {
val editor = TextEditor()
operations.forEach { operation ->
when (operation.first) {
OP_APPEND -> {
editor.append(operation.second!!)
}
OP_DELETE -> {
editor.delete(operation.second!!.toInt())
}
OP_PRINT -> {
editor.print(operation.second!!.toInt())
}
OP_UNDO -> {
editor.undo()
}
}
}
return editor.value
}
fun main(args: Array<String>) {
val scanner = Scanner(System.`in`)
val operations = LinkedList<Pair<Int, String?>>()
repeat(scanner.nextLine().toInt()) {
val operationInput = scanner.nextInt()
operations.add(
operationInput to if (operationInput.hasAdditionalInput) {
scanner.next()
} else {
null
},
)
}
editText(
operations = operations, scanner = scanner
)
}
val Int.hasAdditionalInput: Boolean
get() = when (this) {
OP_APPEND, OP_DELETE, OP_PRINT -> true
OP_UNDO -> false
else -> throw IllegalArgumentException()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment