Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin test if float is in open or semi open range

Tags:

range

kotlin

In Kotlin, is there an idiomatic way to test if a float is in a range where either (or both) the start or the end of the range is exclusive?

E.g. something like

val inRange = 10.f in (0.0f until 20f)

I can't seem to find anything on this in the docs.

How would one deal with semi-open ranges as well?

like image 288
Marius Kohmann Avatar asked Dec 18 '22 18:12

Marius Kohmann


2 Answers

The until function creates the semi-closed integer (not float) range, where the left part is included and the right part is excluded. https://kotlinlang.org/docs/reference/ranges.html

There is closed float ranges support in Koltin https://kotlinlang.org/docs/reference/ranges.html#utility-functions

You may implement that yourself

data class OpenFloatRange(val from: Float, val to: Float)
infix fun Float.open(to: Float) = OpenFloatRange(this, to)
operator fun OpenFloatRange.contains(f: Float) = from < f && f < to

val inRange = 10f in (0.0f open 20f)

Here I use several tricks from Kotlin: https://kotlinlang.org/docs/reference/functions.html#infix-notation https://kotlinlang.org/docs/reference/operator-overloading.html#in

like image 156
Eugene Petrenko Avatar answered Jan 05 '23 14:01

Eugene Petrenko


Inspired by what i selected as answer i came up with this solution, posting it here if anyone wants to reuse it.

class Range(private val fromInclusive: Boolean, val from: Float, val to: Float, private val toInclusive: Boolean) {

    infix fun contains(value: Float): Boolean {
        return when {
            fromInclusive && toInclusive -> value in from..to
            !fromInclusive && !toInclusive -> value > from && value < to
            !fromInclusive && toInclusive -> value > from && value <= to
            fromInclusive && !toInclusive -> value >= from && value < to
            else -> false
        }
    }
}

Usage: val inRange = Range(true, 0f, 10f, false) contains 5f

like image 40
Marius Kohmann Avatar answered Jan 05 '23 14:01

Marius Kohmann