Home 백준 - 5430 AC
Post
Cancel

백준 - 5430 AC

문제

5430 AC

screencapture

kotlin code

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
fun main() {
    q5430()
}

fun q5430() {
    val caseCount = readln().toInt()
    val orders = Array(caseCount) { Order() }
    orders.forEach { it.execOrder() }
}

class Order(private var functionStr: String = String(), private var data: IntArray = intArrayOf()) {
    init {
        readOrder()
    }
    private fun readOrder() {
        setFunctions(readln())
        readln()
        setData(readln())
    }
    private fun setFunctions(functions: String) {this.functionStr = functions}
    private fun setData(data: String) {
        val dataArray = if (data.length < 3) intArrayOf()
        else data.replace("[", "").replace("]", "").split(',').map { it.trim().toInt() }.toIntArray()
        setData(dataArray)
    }
    private fun setData(data: IntArray) { this.data = data }

    fun execOrder() {
        var isReversed = false
        var fromIndex = 0
        var toIndex = data.count()
        for (function in functionStr) when (function) {
            'R' -> isReversed = !isReversed
            'D' -> if (isReversed) toIndex-- else fromIndex++
        }
        printResult(fromIndex, toIndex, isReversed)
    }

    private fun printResult(fromIndex: Int, toIndex: Int, isReversed: Boolean) {
        if (fromIndex > toIndex) {
            println("error")
            return
        }
        val result = if(isReversed) data.getReservedSubArray(fromIndex, toIndex) else data.getSubArray(fromIndex, toIndex)
        println(result.contentToString().replace(" ", ""))
    }
}

private fun IntArray.getSubArray(fromIndex: Int, toIndex: Int) = IntArray(toIndex - fromIndex) { i -> this[fromIndex + i] }

private fun IntArray.getReservedSubArray(fromIndex: Int, toIndex: Int) =  IntArray(toIndex - fromIndex) { i -> this[toIndex - (i + 1)] }
This post is licensed under CC BY 4.0 by the author.

백준 - 2606 바이러스

백준 - 1021 회전하는 큐