Advertisement
Guest User

Untitled

a guest
Jul 19th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. // Needs tests, possible bug?
  2. /**
  3. * @param sizedIntervals - An iterable of pairs representing the size of each interval.
  4. * @return a list of ranges to values such that for all t in [scale.start, scale.end) (semi open range), exists one and
  5. * only pair of range and value (p) in the result list for which t in p's range.
  6. * If scale is not given, then scale is 0..(sum of intervals)
  7. *
  8. * Examples:
  9. * toExclusiveIntervalsList(listOf(0.25 to 'A', 0.25 to 'B', 0.5 to 'C')) =
  10. *
  11. */
  12. fun <T> toExclusiveIntervalsList(sizedIntervals: Iterable<Pair<Double, T>>, scale: ClosedFloatingPointRange<Double>?)
  13. : List<Pair<ClosedFloatingPointRange<Double>, T>> {
  14. val sequence =
  15. sizedIntervals.fold(emptyList<Pair<ClosedFloatingPointRange<Double>, T>>()) { acc, (intervalLength, value) ->
  16. val lastCount: Double = acc.lastOrNull()?.first?.endInclusive?.let { it + it.ulp } ?: 0.0
  17. val nextStart = lastCount + intervalLength
  18. acc.plus((lastCount..(nextStart - nextStart.ulp)) to value)
  19. }
  20. return if (scale == null) sequence
  21. else {
  22. val (minSource, maxSource) = (0.0 to (sequence.lastOrNull()?.first?.endInclusive ?: 0.0))
  23. val (minTarget, maxTarget) = (scale.start to scale.endInclusive)
  24. val offset = minTarget - minSource
  25. val factor = (maxTarget - minTarget) / (maxSource - minSource)
  26. sequence.map { (interval, value) ->
  27. ((offset + (interval.start * factor))..(offset + (interval.endInclusive * factor))) to value
  28. }
  29. }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement