Is there a way to cast a a set of unequal line segments to enum without conditional constructions?

Viewed 40

So, basically, I have implemented a naive rarity system, where I have randomly generated byte values(0-255). From them I determine an enum variable as such:

                case < 100:
                return 0;
            case > 100 and < 180:
                return 1;
                case >180 and <235:
                    return 2;
            case > 235:
                return 3;

So now I'm at the point, where I would like to improve some of my code and this method keeps bothering me. As you can see, values, corresponding to different enum numbers, are unequal. And I started wondering, is there a way to represent this kind of a cast with a formula? I fidgeted a bit with it, but I'm really no mathematician) So I'd appreciate some help

1 Answers

If you want those exact rarity thresholds, then I would write something like rarity1.

If you're a little flexible, you could do rarity2 or rarity3. For rarity2, in essence, we interpret b as a fixed point fraction x ∈ [0, 1) and return ⌊4x²⌋. The boundaries are x = 1/2, x = 1/√2, x = √3/2, i.e., b = 128, b = 182, b = 222.

The rarity3 alternative is not monotone. It takes the min of the upper and lower 2-bit quantities. The outcome probabilities are 7/16, 5/16, 3/16, 1/16, corresponding to decision boundaries 112, 192, 240.

def rarity1(b):
    if b < 100:
        return 0
    elif b < 180:
        return 1
    elif b < 235:
        return 2
    else:
        return 3


def rarity2(b):
    return (b * b) >> 14


def rarity3(b):
    return min(b >> 6, b & 3)
Related