Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make reversed for loop with array index as a start/end point in Kotlin?

now i'm trying to make reversed for a loop.The simple way of reverse for is for(i in start downTo end)

but,what if I use array as a start/end point?

like image 699
Galih indra Avatar asked Aug 19 '18 12:08

Galih indra


People also ask

How do I reverse an array in Kotlin?

To reverse a given string in Kotlin, call reversed() method on this String. reversed() returns a new String with the characters of the original string reversed in order.

How do you reverse a loop in an array?

To loop through an array backward using the forEach method, we have to reverse the array. To avoid modifying the original array, first create a copy of the array, reverse the copy, and then use forEach on it. The array copy can be done using slicing or ES6 Spread operator.


2 Answers

You can loop from the last index calculated by taking size - 1 to 0 like so:

for (i in array.size - 1 downTo 0) {
    println(array[i])
}

Even simpler, using the lastIndex extension property:

for (i in array.lastIndex downTo 0) {
    println(array[i])
}

Or you could take the indices range and reverse it:

for (i in array.indices.reversed()) {
    println(array[i])
}
like image 149
zsmb13 Avatar answered Nov 15 '22 02:11

zsmb13


Additionally to the first answer from zsmb13, some other variants.

Using IntProgression.reversed:

for (i in (0..array.lastIndex).reversed())
    println("On index $i the value is ${array[i]}")

or using withIndex() together with reversed()

array.withIndex()
        .reversed()
        .forEach{ println("On index ${it.index} the value is ${it.value}")}

or the same using a for loop:

for (elem in array.withIndex().reversed())
    println("On index ${elem.index} the value is ${elem.value}")

or if the index is not needed

for (value in array.reversed())
    println(value)
like image 18
DVarga Avatar answered Nov 15 '22 00:11

DVarga