A restricted arrangement of letters in a word
Find number of ways to arrange letters in word "benzine" such that no two same letters are adjacent to each other
This is quite a tough nut to crack. But, there are multiple ways to solve this: by summation, generating function, a recurrence and by integration; summation being the most efficient one.
1 By summation
We'll start with a generalized formula for 5 distinct objects, each with \(n_i\) repetitions. The summation formula can be written as:
and for our problem, we need to find \(N(2,2,1,1,1)\). Putting that in Sage:
\(=660\)
2 Generating function
This is actually just a part of the generating function (which I think can be derived from the recurrence relation)
The coefficient of \(v^2 w^2 x y z\) is the answer (evidently 660).
In Sage:
3 By recurrence
where
In Sage (python will also do), to print out the number of arrangements and its probability of occuring:
NumPy is used here, since it allows array to be manipulated just like in an array programming language like J. The condition checking is made much shorter.
The recurrence is too slow if used for higher values. This can be sped up by caching the computed values, e.g. by dynamic programming.
We may back up our analytical results with a simulation (always a good thing to do, when possible)
a=.1 1 2 2 3 4 5 sim=: 3 : '0=+/0=2-/\(7?7){a' (+/%#)(sim"0)1000000#0 |
about \(0.523729\), which is close to the actual result \(0.523809523809524\).
4 Using Integrals
One more way is to make use of integrals, which actually conveys the summation in a compact representation.
where
\(n_i\) is the number of repetitions of each character in the set.
For our example, the list of \(n_i\) can be written as [2,2,1,1,1]
Hence, in Sage:
var('i') def q(n): return sum((-1)^(i-n)/factorial(i)*binomial(SR(n)-1,SR(i)-1)*x^i, i, 1, n) lst = [2,2,1,1,1] integrate(prod([q(l) for l in lst])*e^-x, x, 0, oo) |
which displays our expected answer.
References: