If I want to have two loops to iterate an array of Int values (to compare them to each other), but I...
c
If I want to have two loops to iterate an array of Int values (to compare them to each other), but I want the inner loop always start at outerIndex++, how would I do that? Currently I have
Copy code
array.forEachIndexed { indexOuter, outer ->
        array.forEachIndexed { indexInnter, inner ->
            //I want this inner forEachIndexed to start at indexOuter++
        }
    }
I thought maybe the inner would be able to do something java-esque like this:
Copy code
for (val indexInner = indexOuter++, indexInner < array.size, indexInner++){
//inner loop stuff
}
j
Copy code
for (i in 1..3) {
    println(i)
}
You can use that as the inner loop and start the range with the outer index and end with the length of the inner array
c
Why does something like this not work?
Copy code
for (outer in array.size){
        println("$outer and ${array[outer]}")
}
I guess im just lost in the kotlin for loop syntax.
i think im holding onto java patterns a bit too much
I ended up with this though. Thanks for the sanity check @Josh Eldridge
Copy code
for (outer in 0 until array.size) {
        for (inner in outer + 1 until array.size) {
            //do stuff with array[outer] and array[inner]
        }
    }
j
The kotlin devs decided to use a different syntax I guess 🤷, glad I could help
❤️ 1
l
not tried this in an REPL or anything, but off the top of my head something like this should work:
Copy code
array.forEachIndexed { idx, outer ->
    array.drop(idx + 1).forEach { inner ->
        //  do stuff with inner and outer
    }
}
probably got an off-by-one error in the
drop(idx + 1)
there....
f
If you are looping over a full collection, you can use
indices
instead of manually specifying the range
Copy code
for (outer in array.indices)