﻿-- chunkname: @scripts/utilities/pseudo_random_distribution.lua

local PseudoRandomDistribution = {}
local P2C
local MAX_PRD_STATE = NetworkConstants.max_prd_state

PseudoRandomDistribution.flip_coin = function (chance, state, seed)
	if chance >= 1 then
		return true, state, seed
	elseif chance <= 0 then
		return false, state, seed
	end

	local c = P2C[math.floor(chance * 100)]
	local math_next_random = math.next_random
	local new_seed, value = math_next_random(seed)

	if value < c then
		new_seed, value = math_next_random(new_seed)

		return value < chance, state, new_seed
	end

	local n = state or math.floor(chance / c)

	new_seed, value = math_next_random(new_seed)

	if value < n * c then
		return true, 1, new_seed
	else
		return false, math.clamp(1 + n, 1, MAX_PRD_STATE), new_seed
	end
end

P2C = {
	0.0001560416916765,
	0.0006200876164356,
	0.0013861777203907,
	0.0024485554716477,
	0.0038016583035531,
	0.0054401086148994,
	0.0073587052890401,
	0.009552415696806,
	0.0120163681507952,
	0.0147458447810727,
	0.0177362748045691,
	0.0209832281625322,
	0.0244824095022856,
	0.028229652481288,
	0.0322209143730877,
	0.0364522709562386,
	0.0409199116686026,
	0.045620135010803,
	0.0505493441851718,
	0.0557040429497818,
	0.0610808317144988,
	0.0666764036215081,
	0.0724875433984468,
	0.0785111206640039,
	0.084744091852317,
	0.091183460913123,
	0.097826380485467,
	0.104670227374915,
	0.1117117582421034,
	0.118949192725404,
	0.1263793161208353,
	0.1340008645349125,
	0.1418051956867528,
	0.1498100879493791,
	0.1579830981257471,
	0.166328776806438,
	0.1749092435951354,
	0.1836246523722508,
	0.1924859579708838,
	0.201547413607754,
	0.2109200313959977,
	0.2203645774003486,
	0.2298986763626535,
	0.2395401522844584,
	0.2493069984401633,
	0.2598723505886277,
	0.270452936701194,
	0.2810076352015464,
	0.2915522666427177,
	0.302103025348742,
	0.3126766393399556,
	0.3232905471447631,
	0.3341199609425926,
	0.3473699930849595,
	0.3603978509331687,
	0.3732168294719914,
	0.3858396117819544,
	0.3982783321856844,
	0.4105446351769761,
	0.4226497308103743,
	0.434604447180966,
	0.4464192805893383,
	0.4581044439647123,
	0.4696699141100894,
	0.4811254783372292,
	0.4924807810774478,
	0.5074626865671641,
	0.5294117647058825,
	0.5507246376811594,
	0.5714285714285715,
	0.591549295774648,
	0.6111111111111113,
	0.6301369863013697,
	0.6486486486486487,
	0.6666666666666666,
	0.6842105263157897,
	0.7012987012987013,
	0.717948717948718,
	0.7341772151898737,
	0.75,
	0.7654320987654323,
	0.7804878048780489,
	0.795180722891566,
	0.8095238095238093,
	0.8235294117647058,
	0.8372093023255812,
	0.850574712643678,
	0.8636363636363638,
	0.8764044943820226,
	0.8888888888888891,
	0.9010989010989011,
	0.9130434782608697,
	0.9247311827956991,
	0.9361702127659574,
	0.9473684210526315,
	0.9583333333333331,
	0.9690721649484535,
	0.979591836734694,
	0.98989898989899,
}

return PseudoRandomDistribution
