dave08
06/12/2018, 1:39 PMfun getPartRanges(partSize: Long, totalSize: Long): List<LongRange>
that returns something like [0..20,21..40,41..60,61..74] for an input of partSize = 20
and totalSize = 74
, what is an ideomatic way to do this in Kotlin?Ricky
06/12/2018, 1:54 PMRicky
06/12/2018, 1:59 PMchunked
or windowed
may help.dave08
06/12/2018, 2:00 PMkarelpeeters
06/12/2018, 2:01 PM(0 until totalSize).chunked(partSize)
karelpeeters
06/12/2018, 2:01 PMtotalSize
and partSize
are actual sizes contrary to your example, otherwise it's ..
instead of until
.Ricky
06/12/2018, 2:04 PMkarelpeeters
06/12/2018, 2:05 PMtoSequence
in there if you want.dave08
06/12/2018, 2:05 PMdave08
06/12/2018, 2:07 PMdave08
06/12/2018, 2:08 PMkarelpeeters
06/12/2018, 2:10 PM(0 .. totalSize/partSize).map { it .. min((1 + it) * partSize, totalSize }
Ricky
06/12/2018, 2:21 PMfun getPartRanges(partSize: Long, totalSize: Long): List<LongRange> {
val fullPartCount = (totalSize / partSize).toInt()
val perfect = totalSize % partSize == 0L
val partRanges = ArrayList<LongRange>(fullPartCount + if (perfect) 0 else 1)
var current = 0L
var next = partSize
while (next < totalSize) {
partRanges += current until next
current = next
next += partSize
}
if (!perfect) partRanges += current until totalSize
return partRanges
}
karelpeeters
06/12/2018, 2:22 PMIdiomaticWrites the most procedural code possible 😉
dave08
06/12/2018, 3:13 PMdave08
06/12/2018, 3:30 PM(0L .. totalSize/partSize).map { (it * partSize) .. min((it * partSize) + partSize + 1, totalSize) }
works! Thanks a lot! And thanks for the try @Ricky, if anything it just goes to show how Kotlin goes a long way 🙂 !