Get Random number, int, float and range - Node.js Number

Node.js examples for Number:Random Number

Description

Get Random number, int, float and range

Demo Code

function Random(seed) {
    var m = 0x80000000;
    var a = 1103515245;
    var c = 12345;

    var state = typeof(seed) !== "undefined" ? seed : Math.floor(Math.random() * (m - 1));

    this.nextInt = function() {
        state = (a * state + c) % m;//from   www.j a v a 2s . c  o  m
        return state;
    };

    this.nextFloat = function() {
        return this.nextInt() / (m - 1);
    };

    this.nextRange = function(start, end) {
        if (!end) {
            end = start;
            start = 0;
        }

        var rangeSize = end - start;
        var randomUnder1 = this.nextInt() / m;
        return start + Math.floor(randomUnder1 * rangeSize);
    };

    this.choice = function(array) {
        return array[this.nextRange(array.length)];
    };
}

Related Tutorials