It's possible to use for loop with double indices in Java, e.g:
for (int j = 0, k = myArray.length - 1; j < myArray.length; j , k--)
To iterate myArray elements from the first element using j and from the last element using k simultaneously without using inner loop. How can we do this in Kotlin without using inner loop.
CodePudding user response:
Kotlin doesn't provide a way to permit what you attempt to do.
Because I imagine your case is purely for exemple, I purpose you two solutions:
1. The good old way
The most optimized for the exemple you give.
for (i in a.indices) {
val j = a.size - 1 - i
println("($i, $j)")
}
(0, 3)(1, 2)(2, 1)(3, 0)
See code snippet on play.kotlinlang.org
2. The .zip() way
Can be usefull on some contexts, the zip method combine two lists of the same size on one list of Tuples which can be used after directly.
val indices = a.indices;
for (i in indices.zip(indices.reversed())) {
println(i)
}
(0, 3)(1, 2)(2, 1)(3, 0)
See code snippet on play.kotlinlang.org
CodePudding user response:
You don't need an inner loop. Just create an additional variable inside for loop.
for(j in myArray.indices) {
val k = myArray.size - 1 - j
// Use j and k here
}
Or alternatively,
var k = myArray.size - 1
for(j in myArray.indices) {
// Use j and k here
k--
}
CodePudding user response:
generateSequence()
is powerful alternative for complex loops. Not so fast as pure for/while loop but very flexible and easy.
generateSequence(
0 to myArray.size - 1 // initial values
) {
it.first 1 to it.second - 1 // new values after each iteration
}.takeWhile {
it.first < myArray.size // limit
}.forEach { (j, k) ->
println("$j $k")
}
And yes, it's good idea to not iterate second variable but calculate it from first (if applicable), as suggested in other answers.