返回列表

根据种子生成随机数 seed random

默认分类 2014/07/29 01:11

一个简单的生成随机数:

function doit(count, min, max, seed){ 
    //todo
    seed = seed === undefined ? new Date().getTime() + Math.random()*1000000000000 : Number(seed);
    min  = min  === undefined ? 0 : Number(min);
    max  = max  === undefined ? 100000000000000 : Number(max);

    var list = [],
        key,
        result = [];

    if (Object.prototype.toString.call(count) !== '[object Array]') {
        count = Number(count);
        for (var i=0,len=count; i<len; i++) {
            list.push(min + i%(max-min));
        }
    }

    count = list;
    list = [];

    for (var i=0,len=count.length; i<len; i++) {
        key = Number(String(((i+seed)*9301+49297)%233280/233280.0).replace('0.', '').substring(6, 7));
        list.push({index: key, value: i});
    }

    var field = 'index',
        order = 'desc';
    list = list.sort(function (a, b) {
        var m, n;
        m = String(a[field]).toLowerCase();
        n = String(b[field]).toLowerCase();

        if (String(parseInt('0' + m, 10)) == m && String(parseInt('0' + n, 10)) == n) {
            m = parseInt(m, 10);
            n = parseInt(n, 10);
        }
        else {
            if (m > n) {
                m = 1;
                n = -m;
            }
            else if (m < n) {
                m = -1;
                n = -m;
            }
            else {
                m = 1;
                n = m;
            }
        }
        return (order == 'desc' ? n - m : m - n);
    });

    for (var i=0,len=list.length; i<len; i++) {
        result.push(count[list[i].value]);
    }
    alert(result);
}