Reputation: 8842
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
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
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
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
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
Reputation: 57381
val r2 = IntRange(0, 100).filter { it %10 ==0 }.map { it /10 }
Upvotes: 1