samedi 16 juillet 2016

Generating Random Numbers for RPG games

I'm wondering if there is an algorithm to generate random numbers that most likely will be low in a range from min to max. For instance if you generate a random number between 1 and 100 it should most of the time be below 30 if you call the function with f(min: 1, max: 100, avg: 30), but if you call it with f(min: 1, max: 200, avg: 10) the most the average should be 10. A lot of games does this, but I simply can't find a way to do this with formula. Most of the examples I have seen uses a "drop table" or something like that.

I have come up with a fairly simple way to weight the outcome of a roll, but it is not very efficient and you don't have a lot of control over it

var pseudoRand = function(min, max, n) {
    if (n > 0) {
        return pseudoRand(min, Math.random() * (max - min) + min, n - 1)
    }

    return max;
}

rands = []
for (var i = 0; i < 20000; i++) {
    rands.push(pseudoRand(0, 100, 1))
}

avg = rands.reduce(function(x, y) { return x + y } ) / rands.length
console.log(avg); // ~50

The function simply picks a random number between min and max N times, where it for every iteration updates the max with the last roll. So if you call it with N = 2, and max = 100 then it must roll 100 two times in a row in order to return 100

I have looked at some distributions on wikipedia, but I don't quite understand them enough to know how I can control the min and max outputs etc.

Any help is very much welcomed




Aucun commentaire:

Enregistrer un commentaire