Kotlin

Kotlin - Combination, Permutation

J_Bin 2022. 4. 22. 11:02

fun main(){

    // permutation
    val list = mutableListOf('a','b','c','d')
    val list2 = permutation(list)
    //println("$list2")

    val list3 = mutableListOf(1, 2, 3, 4, 5)
    val list4 = permutation(list3)
    //list4.forEach { print("$it ") }

    val str = "abcd"
    val list5 = permutation(str.toList())
    //list5.forEach { print("$it ") }
    // permutation



    //combination
    //var arr = listOf(1,2,3,4)                     // 1. Int
    //val answer = mutableListOf<List<Int>>()       // 1. Int

    var arr = "asdf".toList()                       // 2. String
    val answer = mutableListOf<List<Char>>()        // 2. String


    for(i in 1..arr.size){
        combination(answer,arr,Array<Boolean>(arr.size){false},0,i)
    }
    answer.forEach{ println(it)}
    //combination


}


fun <T> permutation(el: List<T>, fin: List<T> = listOf(), sub: List<T> = el ): List<List<T>> {
    return if(sub.isEmpty()) listOf(fin)
    else sub.flatMap { permutation(el, fin + it, sub - it) }
}

fun <T> combination(answer: MutableList<List<T>>, el: List<T>, ck: Array<Boolean>, start: Int, target: Int) {
    if(target == 0) {
        answer.addAll( listOf(el.filterIndexed { index, t -> ck[index] }) )
    } else {
        for(i in start until el.size) {
            ck[i] = true
            combination(answer, el, ck, i + 1, target - 1)
            ck[i] = false
        }
    }
}

'Kotlin' 카테고리의 다른 글

함수형 프로그래밍 #1 ★  (0) 2022.06.13
Kotlin - Any/ 가변인자(vararg)  (0) 2022.06.13
Kotlin - Collection 2  (0) 2022.04.21
[Kotlin - 입력받기, 알고리즘 풀이용]  (0) 2022.04.20
코틀린 zip, getOrElse  (0) 2022.02.28