Created
December 18, 2019 09:23
-
-
Save Krosxx/daafdff4b1c0a6631d587b85afdaca15 to your computer and use it in GitHub Desktop.
kotlin [多层嵌套循环] 转换成一行
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun <T : Comparable<T>> loop(vararg range: Iterable<T>, action: (List<T>) -> Unit) { | |
if (range.isEmpty()) return | |
startLoop(range.size, range, listOf(), action) | |
} | |
fun <T : Comparable<T>> startLoop( | |
rawSize: Int, | |
rs: Array<out Iterable<T>>, | |
ps: List<T>, | |
action: (List<T>) -> Unit | |
) { | |
if (rs.size == 1) { | |
rs[0].forEach { | |
action(ps + it) | |
} | |
return | |
} | |
val tar = Array(rs.size - 1) { | |
rs[it + 1] | |
} | |
rs[0].forEach { | |
startLoop(rawSize, tar, ps + it, action) | |
} | |
} | |
/** | |
* 多层嵌套循环 | |
*/ | |
loop(1..3, 4..6, 7..9) { (a, b, c) -> | |
println(listOf(a, b, c)) | |
} | |
//OutPut: | |
/* | |
[1, 4, 7] | |
[1, 4, 8] | |
[1, 4, 9] | |
[1, 5, 7] | |
[1, 5, 8] | |
[1, 5, 9] | |
[1, 6, 7] | |
[1, 6, 8] | |
[1, 6, 9] | |
[2, 4, 7] | |
[2, 4, 8] | |
[2, 4, 9] | |
[2, 5, 7] | |
[2, 5, 8] | |
[2, 5, 9] | |
[2, 6, 7] | |
[2, 6, 8] | |
[2, 6, 9] | |
[3, 4, 7] | |
[3, 4, 8] | |
[3, 4, 9] | |
[3, 5, 7] | |
[3, 5, 8] | |
[3, 5, 9] | |
[3, 6, 7] | |
[3, 6, 8] | |
[3, 6, 9]*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment