samedi 11 juin 2016

javascript alea random number generator impossible to use in loop?

Am I missing something in the implementation I found (maybe incomplete), or is it normal behaviour for alea script to generate same random numbers in a row when in a loop, because it is using the Date function as base, and in a fast loop I am getting the same date few times in a row?

Utility.prototype.aleaRandom = function()
{
    var s0 = 0;
    var s1 = 0;
    var s2 = 0;
    var c =  1;
    var args = [+new Date];

    var mash = Mash();
    s0 = mash(' ');
    s1 = mash(' ');
    s2 = mash(' ');

    for (var i = 0; i < args.length; i++)
    {
        s0 -= mash(args[i]);
        if (s0 < 0)
        {
            s0 += 1;
        }
        s1 -= mash(args[i]);
        if (s1 < 0)
        {
            s1 += 1;
        }
        s2 -= mash(args[i]);
        if (s2 < 0)
        {
            s2 += 1;
        }
    }

    mash = null;

    var t = 2091639 * s0 + c * 2.3283064365386963e-10; // 2^-32
    s0 = s1;
    s1 = s2;
    s2 = t - (c = t | 0)
    return s2;
};

return Utility;

});

function Mash()
{
    var n = 0xefc8249d;

    var mash = function(data)
    {
        data = data.toString();

        for (var i = 0; i < data.length; i++)
        {
            n += data.charCodeAt(i);
            var h = 0.02519603282416938 * n;
            n = h >>> 0;
            h -= n;
            h *= n;
            n = h >>> 0;
            h -= n;
            n += h * 0x100000000; // 2^32
        }

        return (n >>> 0) * 2.3283064365386963e-10; // 2^-32
    };

  mash.version = 'Mash 0.9';
  return mash;
}


function generate(width, height, chance)
{
    var map = [];

    for(var m = 0; m < width; m++)
    {
        map.push([]);
        for(var n = 0; n < height; n++)
        {
            var rand = utils.aleaRandom();
            //console.log(rand, m, n);
            if(rand < chance)
            {
                //console.log("smaller");
                map[m].push(2);
            }
            else
            {
                //console.log("bigger");
                map[m].push(1);
            }
        }
    }

    return map;
};

When I log numbers it generated in that loop, there are 4-5 the same in a row almost througout entire loop.




Aucun commentaire:

Enregistrer un commentaire