Colton Idle
06/27/2023, 9:38 PMpartition
but I can't give it a true/false predicate. I just want to give it a location.
I tried slice
but it only gives me a list after the index.
I just wanna be able to slice a list into two parts at a given index and get both parts in one shot (that should be more performant than calling slice twice... right?)Youssef Shoaib [MOD]
06/27/2023, 9:43 PMsublist
twice. It returns a view on the list, and so it just results in an object allocation. Do keep in mind that sublist does depend on the list, and so if the list updates, the sublists would update, but that can be simply remedied by copying first before `sublist`ingColton Idle
06/27/2023, 9:46 PMFrancesc
06/27/2023, 10:38 PMtake
and drop
,
val firstN = list.take(n)
val remainder = list.drop(n)
Pihentagy
06/28/2023, 8:01 AMPihentagy
06/28/2023, 8:03 AMPihentagy
06/28/2023, 8:04 AMCLOVIS
06/28/2023, 8:44 AMn until Int.MAX_VALUE
?Klitos Kyriacou
06/28/2023, 8:45 AMCLOVIS
06/28/2023, 8:45 AMslice
expects the end limit to be a valid index. Using take
/`drop` is probably the best, then.CLOVIS
06/28/2023, 8:46 AMString has a substring function that takes one Int argument and returns the substring up to the end.That's
List.drop
CLOVIS
06/28/2023, 8:47 AMlength
/`size` , substring
/`subList` …Fabrizio Scarponi
06/28/2023, 12:45 PMlist.listIterator()
.withIndex()
.forEachRemaining { (index, it) ->
when {
index < list.size / 2 -> println("first half")
else -> println("second half")
}
}
Michael de Kaste
06/28/2023, 1:29 PMval leftBound = n until null
val rightBound = null until n
val open = openRange<Int>() // null until null, typesafe
Michael de Kaste
06/28/2023, 1:30 PMColton Idle
06/28/2023, 1:32 PMCLOVIS
06/28/2023, 1:33 PMfun <T> List<T>.partition(n: Int) =
take(n) to drop(n)
CLOVIS
06/28/2023, 1:33 PMColton Idle
06/28/2023, 1:34 PMCLOVIS
06/28/2023, 1:35 PMCLOVIS
06/28/2023, 1:35 PMKlitos Kyriacou
06/28/2023, 1:44 PMlist.withIndex().partition { it.index <= n }.toList().map { it.map { it.value } }
But it's so unreadable that any of the other solutions are better.CLOVIS
06/29/2023, 6:40 AM