Hi, how can I take elements between two index in a...
# getting-started
g
Hi, how can I take elements between two index in a collection? For example, I have a list of 5 elements and I want to take the second to the fourth elements of this list.
yourList.subList(1, 4)
(toIndex is exclusive)
k
Also keep in mind that if you're doing this on a
MutableList
and you mutate the resulting sublist the original will change too.
g
Thank you !
Is there anyway to optimize this (giving that “tour” is a Set
Copy code
val path = listOf(tour.toList().let {
             it.subList(index, it.size)
        }, tour.toList().subList(0, index)).flatten()
d
I mean... if I understand that correctly, that should be the same as just
tour.toList()
, considering you are making the sub lists 0 to index and then index to size, which will span the whole list. Right?
m
it’s actually reversing the list, e.g
listOf(1, 2, 3,4)
becomes
listOf(3, 4, 1, 2)
k
Revering lists, hmm, I wonder why you'd need that. @GauthierPLM come join us at #advent-of-code!
d
Right, so add a
asReversed
at the end.
g
@karelpeeters i’m trying to solve a TSP problem using the Greedy search algo and the LinKernigan optimisation 🙂 This is part of the LK. I’ll give a look at advent of code and do them when i’ll have time, after finals are over ! 🙂
k
Ah that's funny, we had to reverse part of a list for one of the problems too.