Mohsen Mirhoseini
Mohsen Mirhoseini

Reputation: 8842

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

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?

Upvotes: 4

Views: 3651

Answers (5)

 Ekalips
Ekalips

Reputation: 1491

Answer based on Benito's answer, but adjusted for cases when original starting value is not 0.

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

Upvotes: 1

Ebenezer Asabre
Ebenezer Asabre

Reputation: 11

If your new range does not start from zero, add the first element as below

fun mapRange(number: Int, prevRange: IntRange, newRange: IntRange) : Int {
    val ratio = number.toFloat() / (prevRange.last - prevRange.first)
    return (ratio * (newRange.last - newRange.first) + newRange.first).toInt()
}

Upvotes: 1

LF-DevJourney
LF-DevJourney

Reputation: 28529

I think this should works,

val original = 0..100
val new = original.step((original.endInclusive - original.start) / 9).map{it /10}.forEach{ println(it)}

output,

0
1
2
3
4
5
6
7
8
9

Upvotes: 0

Benito Bertoli
Benito Bertoli

Reputation: 25793

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)

Upvotes: 6

StanislavL
StanislavL

Reputation: 57381

val r2 = IntRange(0, 100).filter { it %10 ==0 }.map { it /10 }

Upvotes: 1

Related Questions