I have looked at various other posts about weighted chance but still find this method much easier to understand than other methods I’ve viewed. I just wanted to make sure this is a correct and efficient way to do this. If you have any suggestions please let me know.
local plrChances = {}
game.Players.PlayerAdded:Connect(function(plr)
local weight = Instance.new("IntValue", plr)
weight.Name = "Weight"
weight.Value = 1
end)
function module.determineSpy(plrs)
local spy
plrChances = {}
for i, plr in pairs(plrs) do
if plr and plr.Character then
for i = plr.Weight.Value, 0, -1 do
table.insert(plrChances, plr)
end
end
end
spy = plrChances[math.random(1, #plrChances)]
for i, v in pairs(plrs) do
if v == spy then
v.Weight.Value = 1
else
v.Weight.Value += 1
end
end
return spy
end
keep in mind this should be in #help-and-feedback:code-review
anyways you can probably just combine both of the for loops imo
Summary
local plrChances = {}
game.Players.PlayerAdded:Connect(function(plr)
local weight = Instance.new("IntValue", plr)
weight.Name = "Weight"
weight.Value = 1
end)
function module.determineSpy(plrs)
local spy
plrChances = {}
for _, plr in pairs(plrs) do
if plr and plr.Character then
plr.Weight.Value += 1
for _ = plr.Weight.Value, 0, -1 do
table.insert(plrChances, plr)
end
end
end
spy = plrChances[math.random(1, #plrChances)]
spy.Weight.Value = 1
return spy
end
basically we can just add the weight in the first for loop, and then set the spy to be weight 1 later.
this makes it more performant too
yes youre right. although it wouldnt affect the outcome id say this is more suitable as the weight isnt changed before the for loop
function module.determineSpy(plrs)
local spy
plrChances = {}
for i, plr in pairs(plrs) do
if plr and plr.Character then
for i = plr.Weight.Value, 0, -1 do
table.insert(plrChances, plr)
end
plr.Weight.Value += 1
end
end
spy = plrChances[math.random(1, #plrChances)]
spy.Weight.Value = 1
return spy
end