Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
22
Task/Permutations/Kotlin/permutations-1.kotlin
Normal file
22
Task/Permutations/Kotlin/permutations-1.kotlin
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
// version 1.1.2
|
||||
|
||||
fun <T> permute(input: List<T>): List<List<T>> {
|
||||
if (input.size == 1) return listOf(input)
|
||||
val perms = mutableListOf<List<T>>()
|
||||
val toInsert = input[0]
|
||||
for (perm in permute(input.drop(1))) {
|
||||
for (i in 0..perm.size) {
|
||||
val newPerm = perm.toMutableList()
|
||||
newPerm.add(i, toInsert)
|
||||
perms.add(newPerm)
|
||||
}
|
||||
}
|
||||
return perms
|
||||
}
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
val input = listOf('a', 'b', 'c', 'd')
|
||||
val perms = permute(input)
|
||||
println("There are ${perms.size} permutations of $input, namely:\n")
|
||||
for (perm in perms) println(perm)
|
||||
}
|
||||
18
Task/Permutations/Kotlin/permutations-2.kotlin
Normal file
18
Task/Permutations/Kotlin/permutations-2.kotlin
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
fun <T> List<T>.rotateLeft(n: Int) = drop(n) + take(n)
|
||||
|
||||
fun <T> permute(input: List<T>): List<List<T>> =
|
||||
when (input.isEmpty()) {
|
||||
true -> listOf(input)
|
||||
else -> {
|
||||
permute(input.drop(1))
|
||||
.map { it + input.first() }
|
||||
.flatMap { subPerm -> List(subPerm.size) { i -> subPerm.rotateLeft(i) } }
|
||||
}
|
||||
}
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
permute(listOf(1, 2, 3)).also {
|
||||
println("""There are ${it.size} permutations:
|
||||
|${it.joinToString(separator = "\n")}""".trimMargin())
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue