Is there any method in Kotlin which allow me to translate a value from a range into another range?

Issue

I have a value inside a range of numbers (for instance 0..100) which I want to translate it into another range, (for instance to 0..9). So the result would be:

50 -> 4 or 100 -> 9, …

Is there any method in Kotlin which helps me in this regard?

Solution

Calculate the ratio of the number within the original range.
Multiply it by the second range.

fun convert(number: Int, original: IntRange, target: IntRange): Int {
    val ratio = number.toFloat() / (original.endInclusive - original.start)
    return (ratio * (target.endInclusive - target.start)).toInt()
}

As an extension function

fun IntRange.convert(number: Int, target: IntRange): Int {
    val ratio = number.toFloat() / (endInclusive - start)
    return (ratio * (target.endInclusive - target.start)).toInt()
}

val result =  (0..100).convert(50, 0..9)

Answered By – Benito Bertoli

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.