Created
October 17, 2022 15:30
-
-
Save xyberviri/0a4aaa0866a20bd3bf6ddd30d2663411 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--Cumulative Distribution Function | |
--Author: Xyberviri#5609 | |
--License: GNU GPL v3 | |
--Legal: https://tldrlegal.com/license/gnu-general-public-license-v3-(gpl-3) | |
local function GetRandomLoot(loottable) | |
local totalweights = 0 --Precompute this value for optimization | |
for Pick, Chance in pairs(loottable) do | |
totalweights = totalweights + Chance | |
end | |
local rand = ZombRand(1,totalweights) | |
local weight = 0 | |
for Pick, Chance in pairs(loottable) do | |
weight = weight + (Chance * 10) | |
if weight >= rand then | |
return Pick | |
end | |
end | |
end | |
--Example: | |
local PartTable = { | |
["none"] = 70, | |
["ZomboidExtract.ZEZombieBrain"] = 10, | |
["ZomboidExtract.ZEZombieHeart"] = 10, | |
["ZomboidExtract.ZEZombieLung"] = 10, | |
["ZomboidExtract.ZEZombieKidney"] = 10, | |
["ZomboidExtract.ZEZombieLiver"] = 10, | |
["ZomboidExtract.ZEZombieBone"] = 10, | |
["ZomboidExtract.ZEZombieFlesh"] = 10, | |
} | |
local item = GetRandomLoot(PartTable) | |
if item ~= "none" then | |
player:getInventory():AddItem(item) | |
end | |
--Cumulative Distribution Function (Optimized) | |
--Author: Xyberviri#5609 | |
--License: GNU GPL v3 | |
--Legal: https://tldrlegal.com/license/gnu-general-public-license-v3-(gpl-3) | |
local function GetRandomLoot(loottable,totalweights) | |
local rand = ZombRand(1,totalweights) | |
local weight = 0 | |
for Pick, Chance in pairs(loottable) do | |
weight = weight + (Chance * 10) | |
if weight >= rand then | |
return Pick | |
end | |
end | |
end | |
--Example (Optimized): | |
local item = GetRandomLoot(PartTable,140) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment