[Kotlin] Algorithm - Combination
Combination
Choose r from different n elements without duplication and list them in order.

Process
Select (fixed) an element from the array.
Find and paste the combination based on the remaining arrangements.
Repeat the above procedure until the number of combined elements (recursive call depth) matches r.
![The number of all three combinations in an array [A, B, C, D]](/image/2023/09/20230926153725_000.webp)
The number of all three combinations in an array [A, B, C, D]
Code 1
Kotlin
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
private const val alphabets = "ABC"
private val results = mutableListOf<Char>() // Altered Alphabet
fun main() {
combination(2)
}
/**
* Combination
* @param count: Number to be extracted
* @param index: The index to begin the search. Numbers already extracted do not need to be checked again because they do not take into account the order.
* @param depth: Number of Extracted
*/
fun combination(count: Int = 0, index: Int = 0, depth: Int = 0) {
if (depth == count) {
println("[${results.joinToString(", ")}]") // a complete combination
return
}
for (i in index until alphabets.length) {
results.add(alphabets[i])
combination(count, i + 1, depth + 1)
results.removeAt(results.lastIndex)
}
}Code 2. Compatible with all data types with generic types
Kotlin
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
fun main() {
combination(arrayOf("A", "B", "C"), 2).forEach {
println(it)
}
}
fun <T> combination(elements: Array<T>, r: Int): List<List<T>> {
val n = elements.size
val results = mutableListOf<List<T>>() // the number of all cases
val result = elements.sliceArray(0 until r)
fun recursionCombination(depth: Int = 0, index: Int = 0) {
if (depth == r) {
results.add(result.toList())
return
}
for (i in index until n) {
result[depth] = elements[i]
recursionCombination(depth + 1, i + 1)
}
}
recursionCombination()
return results
}Result
Plain Text
1
2
3
[A, B]
[A, C]
[B, C]Reference
https://velog.io/@chayezo/Algorithm-순열-조합
https://hanyeop.tistory.com/455
https://notepad96.tistory.com/111
https://gyeong-log.tistory.com/51
https://soopeach.tistory.com/157
https://velog.io/@heyday_7/알고리즘-순열과-조합

민갤
Back-End Developer
백엔드 개발자입니다.

[Kotlin] Algorithms - Permutation
Implement algorithm combinations, permutations, and redundant pure blood in kotlin
Kotlin

[Kotlin] Korean Coding Test - Programmers - Taking a group photo
Programmus Coding Test Take a Group Photo
Kotlin
