Lua 数组洗牌算法(Fisher-Yates)代码优缺点分析

以下是使用 Fisher-Yates 算法实现数组洗牌的 Lua 代码,并分析其优缺点:

function GenRondomSeed( nRondomExt)
    math_randomseed( tonumber( tostring(os_time() + nRondomSeedValue + nRondomExt):reverse():sub(1, 6)))  
    math_random()
    math_random()
    math_random()
    nRondomSeedValue = nRondomSeedValue + 1
    if nRondomSeedValue > 1000 then
        nRondomSeedValue = 1
    end
end

function ShuffleArray_Fisher_Yates( tId)
    if not tId or #tId == 0 then
        return
    end

    local i = #tId
    local j,temp
 
    if i == 0 then
        return
    end

    GenRondomSeed( i)

    while i > 0 do 
        j = math_random(i)
        temp = tId[i]
        tId[i] = tId[j]
        tId[j] = temp

        i = i - 1
    end
end

优点:

  1. 实现了 Fisher-Yates 洗牌算法,可以随机打乱数组的顺序;
  2. 在洗牌之前调用了 GenRondomSeed 函数,以确保随机数的随机性。

缺点:

  1. GenRondomSeed 函数实现过于复杂,使用了多个函数调用和字符串操作,可能会影响代码的可读性和可维护性;
  2. GenRondomSeed 函数中使用了全局变量 nRondomSeedValue,可能会引起命名空间污染和不必要的状态共享;
  3. 在调用 math_random 函数之前,没有检查 math_randomseed 函数是否成功调用,可能会导致随机数生成失败;
  4. ShuffleArray_Fisher_Yates 函数中,当数组为空或长度为零时,直接返回,可能会隐藏一些错误或异常情况。

优化建议:

  1. 简化 GenRondomSeed 函数,使用更简洁的随机数生成方法,例如:
    function GenRondomSeed( nRondomExt)
        math.randomseed(os.time() + nRondomSeedValue + nRondomExt)
        math.random()  -- 丢弃前几个随机数
    end
    
  2. 使用局部变量代替全局变量 nRondomSeedValue,避免命名空间污染;
  3. 在调用 math_random 函数之前,检查 math_randomseed 函数的返回值,以确保随机数生成成功;
  4. ShuffleArray_Fisher_Yates 函数中,对数组为空或长度为零的情况进行显式处理,例如抛出错误或返回错误信息。

通过以上优化,可以提高代码的可读性、可维护性和健壮性。

Lua 数组洗牌算法(Fisher-Yates)代码优缺点分析

原文地址: https://www.cveoy.top/t/topic/lKzt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录