# 游戏里面的容斥原理

math.randomseed(tostring(os.time()):reverse():sub(1, 6))

local counts = {}

local p1, p2, p3 = 0.2, 0.3, 0.5

for j=1, 10000 do
local a1, a2, a3 = 0, 0, 0

for i=1,1000000 do
local r = math.random()
if r > p3 then
a3 = a3 + 1
elseif r > p2 then
a2 = a2 + 1
else
--elseif r > p1 then
a1 = a1 + 1
end

if a1 > 0 and a2 > 0 and a3 > 0 then
table.insert(counts, i)
break
end
end
end

print(avg_count/#counts) --打印结果,当然你不一定是这个值:6.6702

print(1/p1+1/p2+1/p3 - 1/(p1+p2) - 1/(p2+p3) - 1/(p1+p3) + 1/(p1+p2+p3))

--传入数组,取里面的几个元素进行组合
local function combine(arr, n, m, b, result)
n = n or #arr
--print(' combine', n, m, arr[n])
assert(n >= m)
for i=m, n, 1 do
b[m] = i
if m > 1 then
combine(arr, i - 1, m - 1, b, result)
else
--用于打印
local s = {}
table.foreach(b,function(_,v)
table.insert(s,arr[v])
end)
table.insert(result, s)
end
end
end

--combine({'a','b','c', 'd'},nil,2,{})

--将数组相加
assert(type(arr)=='table')
local r = 0
for i,v in pairs(arr) do
r = r + v
end
return r
end

--容斥原理
function InclusionExclusion (ppp)
local result = 0
for i,v in ipairs(ppp) do
result = result + 1/v
end

local count = #ppp
for i=2,count - 1 do
local c = {}
combine(ppp, nil, i, {}, c)
--遍历所有的组合
table.foreach(c, function(_,v)
--计算组合里面所有的数
print(InclusionExclusion({p1,p2,p3}) --打印值:6.6547619047619