Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Needs tests, possible bug?
- /**
- * @param sizedIntervals - An iterable of pairs representing the size of each interval.
- * @return a list of ranges to values such that for all t in [scale.start, scale.end) (semi open range), exists one and
- * only pair of range and value (p) in the result list for which t in p's range.
- * If scale is not given, then scale is 0..(sum of intervals)
- *
- * Examples:
- * toExclusiveIntervalsList(listOf(0.25 to 'A', 0.25 to 'B', 0.5 to 'C')) =
- *
- */
- fun <T> toExclusiveIntervalsList(sizedIntervals: Iterable<Pair<Double, T>>, scale: ClosedFloatingPointRange<Double>?)
- : List<Pair<ClosedFloatingPointRange<Double>, T>> {
- val sequence =
- sizedIntervals.fold(emptyList<Pair<ClosedFloatingPointRange<Double>, T>>()) { acc, (intervalLength, value) ->
- val lastCount: Double = acc.lastOrNull()?.first?.endInclusive?.let { it + it.ulp } ?: 0.0
- val nextStart = lastCount + intervalLength
- acc.plus((lastCount..(nextStart - nextStart.ulp)) to value)
- }
- return if (scale == null) sequence
- else {
- val (minSource, maxSource) = (0.0 to (sequence.lastOrNull()?.first?.endInclusive ?: 0.0))
- val (minTarget, maxTarget) = (scale.start to scale.endInclusive)
- val offset = minTarget - minSource
- val factor = (maxTarget - minTarget) / (maxSource - minSource)
- sequence.map { (interval, value) ->
- ((offset + (interval.start * factor))..(offset + (interval.endInclusive * factor))) to value
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement