Foggy day

Kotlin - recursive function -1 본문

Kotlin

Kotlin - recursive function -1

jinhan38 2021. 3. 21. 17:46
class KotlinPlayGroundActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_kotlin_play_ground)

        val lists = listOf<Char>('a', 'b', 'c', 'd', 'e')
        println("toString : ${toString(lists, "text")}")
        println("toStringSecond : ${toStringSecond(lists, "text")}")
        println("toStringThird : ${toStringThird(lists, "text")}")

    }

    fun toString(list: List<Char>, s: String): String =
        if (list.isEmpty())
            s
        else
            toString(list.subList(1, list.size), append(s, list[0]))


    fun toStringSecond(list: List<Char>, s: String): String =
        if (list.isEmpty())
            s
        else
            toStringSecond(list.drop(1), append(s, list.first()))


    fun toStringThird(list: List<Char>, s: String): String =
        if (list.isEmpty())
            s
        else
            prepend(list[0], toStringThird(list.subList(1, list.size), s))


    fun append(s: String, c: Char): String = "$s $c"
    fun prepend(c: Char, s: String): String = "$c $s"
    
}