random - Lua - Getting one value from a table and assigning it to another with no repeats -


specifically, garry's mod, don't think matters in problem. want 1 player, , set value random player (so every player has random 'target'). want no repeats, , player not assigned self. better illustrate:

player assigning illustation.

the difference picture want each player assigned random player, more player1 => player 5, player 3 => player 2, etc.

here code @ moment, leaves 1 person unpicked:

validtargets = {} targetlist = {}  local swap = function(array, index1, index2)     array[index1], array[index2] = array[index2], array[index1] end  getshuffle = function(numelems)     local shuffle = {}     = 1, numelems         shuffle[#shuffle + 1] =     end     ii = 1, numelems         swap(shuffle, ii, math.random(ii, numelems))             end     return shuffle end  function assigntargets()     local shuffle = getshuffle(#playing)     k,v in ipairs(shuffle)         targetlist[k] = v     end      synctargets() end  function synctargets()     k,v in pairs(targetlist)         net.start("sendtarget")             net.writeentity(v)         net.send(k)     end end 

i have lua function generates random shuffle of numbers 1 n, given n. method based on popular algorithm generate random permutation of array of elements .

you can try using so:

local swap = function(array, index1, index2)     array[index1], array[index2] = array[index2], array[index1] end   getshuffle = function(numelems)     local shuffle = {}     = 1, numelems         shuffle[#shuffle + 1] =     end     ii = 1, numelems         swap(shuffle, ii, math.random(ii, numelems))             end     return shuffle end  function assigntargets()     local shuffle = getshuffle(#playing) --assuming `playing` known global     k,v in ipairs(shuffle)         targetlist[k] = v     end end 

Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -