I am working on the software for a machine that will automatically trim toenails, so that users can simply put their feet in it and run it instead of having to manually do i
Actually, I like your original algorithm best.
Since 14 out of 120 permutations work, 106 out of 120 do not. So each check has a 106/120 chance of failing.
That means the expected number of failures is:
1*(106/120) + 2*(106/120)^2 + 3*(106/120)^3 + ...
Not too hard to sum this infinite series:
S = 1*x + 2*x^2 + 3*x^3 + ...
Multiply through by x:
x*S = 1*x^2 + 2*x^3 + ...
Subtract:
S - x*S = x + x^2 + x^3 + ...
Multiply through by x again and subtract again:
x*S - x^2*S = x^2 + x^3 + ...
S - 2*x*S + x^2S = x
S*(1-x)^2 = x
S = x/(1-x)^2
Since x = 106/120, S = 64.9.
So, on average your loop needs only 65 iterations to find a solution.
What is the probability that it takes, say, one thousand iterations?
Well, the probability of failing any single iteration is 104/120, so the probability of failing 1000 iterations is (104/120)^1000, which is something like 10^(-63). That is, you will never see it happen in your lifetime, and probably not in the lifetime of the universe.
No precomputed tables, easy adaptation to different numbers of fingers/toes/hands/feet, easy adaptation to different rulesets... What's not to like? Exponential decay is a wonderful thing.
[update]
Whoops, I did get the original formula wrong... Since my probabilities do not sum to 1. :-)
The correct expression for the expected number of failures is:
0*(14/120) + 1*(106/120)*(14/120) + 2*(106/120)^2*(14/120) + ...
(For example, to get exactly two failures, you need two failures followed by a success. Two failures have probability (106/120)^2; one success has probability (14/120); multiply those together to get the weight for the "2" term.)
So my S is off by a factor of (1-x) (i.e., 14/120). The actual expected number of failures is just x/(1-x) = 106/14 = 7.57. So on average it takes only 8-9 iterations to find a solution (7.5 failures plus one success).
My math for the "1000 failures" case is still correct, I think.