用lua實現的不重復隨機數


空間復雜度為(1-n),時間復雜度為應該也是最低的,lua方便之處還是很值得利用的

local Random = {};

 

function Random:Awake()

    self.m_min = 1;

    self.m_max = 1;

    self.m_end = 1;

    self.m_rangeMap = {};

end

 

function Random:setRange( min,max )

    if min > max then

        min,max = max ,min;

    end

    self.m_min = min;

    self.m_max = max;

    self.m_end = max;

    self.m_rangeMap[self.m_max] = self.m_max;

end

-------------------不重復------------------------------

function Random:getRandom( ... )

    math.randomseed(tostring(os.time()):reverse():sub(1,6));--避免時差太小

    math.random(self.m_min,self.m_max);--過濾掉前幾個劣質隨機數;

    math.random(self.m_min,self.m_max);

    math.random(self.m_min,self.m_max);

    local tmp = math.random(self.m_min,self.m_max);

    local ret = self.m_rangeMap[tmp];

    if ret == nil then

        ret = tmp;

    end

    self.m_rangeMap[tmp] = self.m_max;

    self.m_max = self.m_max - 1;

    return ret;

end

 

function Random:getRandomNormal( ... )

    math.randomseed(tostring(os.time()):reverse():sub(1,6));--避免時差太小

    math.random(self.m_min,self.m_end);--過濾掉前幾個劣質隨機數;

    math.random(self.m_min,self.m_end);

    math.random(self.m_min,self.m_end);

    local ret = math.random(self.m_min,self.m_end);

    local tmp = self.m_rangeMap[ret];

    if tmp == nil then

        self.m_rangeMap[ret] = self.m_max;

        self.m_max = self.m_max - 1;

    end

    return ret;

end

 

return Random;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM