holgerbrandl
05/10/2023, 5:35 AMval items = (1..10).shuffled()
val from =3
val to =7
val from3o7Incl = items.dropWhile { it != from }.takeWhile { it != to } + listOf(to)Wout Werkman
05/10/2023, 5:52 AMasSequence. Now it won't make intermediate lists, and it will not iterate any values after to.
val from3o7Incl = items.asSequence().dropWhile { it != from }.takeWhile { it != to } + sequenceOf(to)
If you are working on the JVM and you use a sorted set, you can efficiently lookup the range by calling sortedSet.subSet(from, to). Iterating this subset will have O(log(N) + M) time complexity, with N being the size of your initial set, and M being the size of the subset.
If it's a sorted list or array, you can use items.subList(items.binarySearch(from), items.binarySearch(to)) for the same O(log(N) + M) time complexity. You will need to handle the cases when from and to are not in itemsholgerbrandl
05/10/2023, 6:15 AMfrom and end are in items which is list of item.
Using subList or subSet felt a bit wrong to be, since I naively I would just need to traverse the list once to figure the subset. so it should be something like O(n) if the list is sorted and I'm sure that both from and end are included and showing up in order.
Essentially what I am hoping for is a flavor of takeWhile which is inclusive of the last element where the predicate fails. Something like ``takeWhileWithLast` ...Wout Werkman
05/10/2023, 6:27 AMUsingWell, you are in luck, bothorsubListfelt a bit wrong to be, since I naively I would just need to traverse the list once to figure the subset. so it should be something likesubSetif the list is sorted and I'm sure that both from and end are included and showing up in order.O(n)
subList aswell as `TreeSet`'s subSet functions only return a view. While might be dangerous in case of mutations to the original Essentially what I am hoping for is a flavor ofThis does not exist unfortunately, you'd have to add such extension method yourself.which is inclusive of the last element where the predicate fails. Something like ``takeWhileWithLast` ...takeWhile
holgerbrandl
05/10/2023, 6:33 AMJoffrey
05/10/2023, 7:06 AMholgerbrandl
05/10/2023, 7:10 AMWout Werkman
05/10/2023, 7:26 AM