Permutations: Difference between revisions
Content added Content deleted
m (→{{header|AppleScript}}: →Recursive again: Minor optimisations and cosmetics.) |
|||
Line 4,935: | Line 4,935: | ||
[d, c, a, b] |
[d, c, a, b] |
||
[d, c, b, a] |
[d, c, b, a] |
||
</pre> |
|||
=== Using rotate === |
|||
<syntaxhighlight lang="kotlin"> |
|||
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()) |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
There are 6 permutations: |
|||
[3, 2, 1] |
|||
[2, 1, 3] |
|||
[1, 3, 2] |
|||
[2, 3, 1] |
|||
[3, 1, 2] |
|||
[1, 2, 3] |
|||
</pre> |
</pre> |
||