Advertisement
wolfboyft

alive-rng-test.lua

Sep 22nd, 2022
860
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.88 KB | None | 0 0
  1. local numCount = 4
  2. local target = 100
  3.  
  4. -- Generate numbers from 0 to 1
  5. local nums = {}
  6. for i = 1, numCount do
  7.   nums[i] = math.random()
  8. end
  9.  
  10. -- Get their total
  11. local total = 0
  12. for i, v in ipairs(nums) do
  13.     total = total + v
  14. end
  15.  
  16. -- Replace each number with the floor of target * original / previous total while getting new total
  17. local total2 = 0
  18. for i, v in ipairs(nums) do
  19.     nums[i] = math.floor(target * v / total)
  20.     total2 = total2 + nums[i]
  21. end
  22.  
  23. -- Spread the remainder evenly (ish, could involve random here but this is good enough)
  24. -- This repeating loop could probably be replaced with just a loop that goes over every number once
  25. local i = 1
  26. for _ = 1, target - total2 do
  27.     nums[i] = nums[i] + 1
  28.     i = (i - 1 + 1) % numCount + 1
  29. end
  30.  
  31. -- Check final total
  32. local total3 = 0
  33. for i, v in ipairs(nums) do
  34.     total3 = total3 + nums[i]
  35. end
  36.  
  37. print(target == total3)
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement