从表中获取一个值,并将其分配给另一个值,确保没有重复。

具体来说,这是针对Garry's Mod的,但我认为对这个问题并不太重要。我想要做的是选定一个玩家,并将他们的值设置为另一个随机玩家(因此每个玩家都有一个随机的“目标”)。我想要实现的是没有重复,并且某个玩家不能分配给自己。为了更好地说明:

Player assigning illustation.

唯一的区别是我希望将每个玩家分配给另一个随机玩家,类似于player1 => player5,player3 => player2等等。

这是我目前的代码,但这总是留下一个人未选择:

validTargets = {}
TargetList = {}

local Swap = function(array, index1, index2)
    array[index1], array[index2] = array[index2], array[index1]
end

GetShuffle = function(numelems)
    local shuffle = {}
    for i = 1, numelems do
        shuffle[#shuffle + 1] = i
    end
    for ii = 1, numelems do
        Swap(shuffle, ii, math.random(ii, numelems))
    end
    return shuffle
end

function assignTargets()
    local shuffle = GetShuffle(#playing)
    for k,v in ipairs(shuffle) do
        TargetList[k] = v
    end

    SyncTargets()
end

function SyncTargets()
    for k,v in pairs(TargetList) do
        net.Start("sendTarget")
            net.WriteEntity(v)
        net.Send(k)
    end
end
点赞
用户988143
用户988143

我有一个lua函数,它根据给定的n生成从1到n的随机乱序数字。该方法基于一种流行的算法来生成元素数组的随机排列。

您可以这样尝试使用:

local Swap = function(array, index1, index2)
    array[index1], array[index2] = array[index2], array[index1]
end

GetShuffle = function(numelems)
    local shuffle = {}
    for i = 1, numelems do
        shuffle[#shuffle + 1] = i
    end
    for ii = 1, numelems do
        Swap(shuffle, ii, math.random(ii, numelems))
    end
    return shuffle
end

function assignTargets()
    local shuffle = GetShuffle(#playing) --假设`playing`是已知的全局变量
    for k,v in ipairs(shuffle) do
        TargetList[k] = v
    end
end
2014-06-10 16:26:02