#/usr/bin/env julia
function factorial( n::Integer )::Integer
if n == 0
return 1
elseif n < 0
error("put negative number in factorial")
end
return Integer( reduce(*, 1:n) )
end
#n/(k1!*k2!*k3!) .....
function divide_by_fact(n)::Integer
nLength = length(n)
if nLength <= 0
error("illegal input")
end
nSet = Set(n)
nBag = Dict( key => 0 for key in nSet )
for each = n
nBag[each] += 1
end
step01 = factorial(nLength)
step02 = reduce(*, map(factorial,values(filter((k,v)-> v != 1, nBag))))
return Integer( step01 / step02 )
end
function combin(n, r::Integer)::Integer
nLength = length(n)
if nLength < 0 || r >= nLength
error(" combin argument require ( n > 0 and r <= n )")
end
return Integer( factorial(nLength) / (factorial(r) * factorial(nLength - r)) )
end
function binomial_coefficient(n, t, exponet::Integer)::Real
nLength = length(n)
tLength = length(t)
if (nLength == tLength == 2
&& exponet > 0
&& reduce( (a,b)-> a && b , map(eachN -> typeof(eachN) <: Real , n))
&& reduce( (a,b)-> a && b , map(eachT -> typeof(eachT) <: Integer , t)) )
k = exponet - t[1]
return combin(1:exponet, k) * ( n[1] ^ t[1] ) * ( n[2] ^ t[2] )
elseif exponet == 0
return 1
else
error("illegal input")
end
end
function multinomial_coefficient(n, t, exponet::Integer)::Real
nLength = length(n)
tLength = length(t)
if (nLength == tLength > 2
&& exponet > 0
&& reduce( (a,b)-> a && b , map(eachN -> typeof(eachN) <: Real , n))
&& reduce( (a,b)-> a && b , map(eachT -> typeof(eachT) <: Integer , t)) )
return ( factorial(exponet)/(reduce(*, map(factorial, t)))
* reduce(*, [a^b for (a, b) in zip(n, t)]) )
elseif exponet == 0
return 1
else
error("illegal input")
end
end
ans1 = combin(1:10, 6)
qStr = "TALLAHASSEE"
filterCharA = filter(a-> a != 'A', qStr)
lengthOfFilterCharA = length( filterCharA )
howManyCharAInQStr = length(filter(a-> a == 'A', qStr))
ans2 = divide_by_fact(filterCharA) * combin( 1:(lengthOfFilterCharA + 1) , howManyCharAInQStr)
ans3 = binomial_coefficient([1,2], [2,5], 7 )
ans4 = multinomial_coefficient([2,3,4], [2,5,3], 6 )
println("""
EX:
c(10, 6) = ?
sol: {$ans1}
EX:
TALLAHASSEE 這些安排方法中有 A不相鄰多少種
sol: {$ans2}
EX:
A: (x + 2y)⁷ => x²y⁵ 的係數為
B: (2x + 3y + 4z)⁶ => x²y⁵z³
sol:
A = {$ans3}
B = {$ans4}
EOF
""")