Given x (values from 0..Int.MAX_VALUE), when `x in...
# mathematics
s
Given x (values from 0..Int.MAX_VALUE), when
x in 0 until a
, return 0,
a until b
return 1,
b until c
return 2, greater than or equal to
d
, return 3?
g
What's the question exactly? Do you want a snippet that does what you said? Then here it is:
Copy code
when(x) {
    x in 0 until a -> return 0
    x in a until b -> return 1
    x in b until c -> return 2
    x >= d -> return 3
}
But I think you should ask such questions in #getting-started. There is no specific mathematical context.
s
I was looking for something without branching. I tried using modulo to no success.
g
Well, if you have branching in your algorithm, but you do not want to write the branching it means that you have to either find equivalent algorithm or wrap this branching into something to replace the branching with something else (like maps with defaults replace
map.getOrNull(key) ?: default
). IMO, replacing branching in this case is just making your life harder and your code less readable. As for equivalent algorithm you can use
Copy code
(min(a, x) - min(a-1, x) + min(b, x) - min(b-1, x) + 2 * (min(c, x) - min(c-1, x)) + min(d-1, x) - min(d, x)).let { if (it != 4) return it }
As for wrapping I can not come up with any idea.