https://kotlinlang.org logo
Title
g

GauthierPLM

12/13/2017, 1:34 PM
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

karelpeeters

12/13/2017, 1:36 PM
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

GauthierPLM

12/13/2017, 1:39 PM
Thank you !
Is there anyway to optimize this (giving that “tour” is a Set
val path = listOf(tour.toList().let {
             it.subList(index, it.size)
        }, tour.toList().subList(0, index)).flatten()
d

diesieben07

12/13/2017, 1:58 PM
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

menegatti

12/13/2017, 2:14 PM
it’s actually reversing the list, e.g
listOf(1, 2, 3,4)
becomes
listOf(3, 4, 1, 2)
k

karelpeeters

12/13/2017, 2:16 PM
Revering lists, hmm, I wonder why you'd need that. @GauthierPLM come join us at #advent-of-code!
d

diesieben07

12/13/2017, 2:16 PM
Right, so add a
asReversed
at the end.
g

GauthierPLM

12/13/2017, 2:55 PM
@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

karelpeeters

12/13/2017, 3:06 PM
Ah that's funny, we had to reverse part of a list for one of the problems too.