lundi 13 août 2018

Filtering Enum of chances and selecting one based on a random chance

Hello I'm trying to filter through the following enum to select one of the values based on a random chance.

 enum class rewardType(var chance : Float, var tier : Int) {
    TIER_1(60.0F,0),
    TIER_2(45.0F,1),
    TIER_3(20.0F,2),
    TIER_4(10.0F,3),
    TIER_5(2.0F,4),
    TIER_6(1.0F,5)

}

At the moment i'm selecting a value using this code.

                val ( tier, tierChance) =
                    rewardType.values()
                    .filter { it.chance.passRandom() }
                    .map { Pair(it.chance, it.tier) }

There are my random utility functions also

val random = ThreadLocalRandom.current()!!

fun randomChance(value: Float) = random.nextFloat() * value

fun Float.passRandom() = randomChance(100F) < this

At the moment the majority of the time it will accurately select one of the tier values with no issue. However around %15 of the time i will get an IndexArrayOutOfBounds. I know that this is because the chances in the enum are spread to far apart(Because if i add more values to the enum so the chances aren't spread out as much as they are then this Exception doesn't occur)

How do i go about fixing this error? or is there a whole better way of doing this?




Aucun commentaire:

Enregistrer un commentaire