#!/usr/bin/env python
#
# Copyright 2010 Douwe M Osinga
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Program to simulate the abracadabra puzzle.

    'A long time ago a good friend of mine told me this puzzle. 
     Let’s say there is a monkey hitting a typewriter at random.
     And let’s assume he is only hitting letters and that the
     chance for each letter to get hit is equal. Do you have to
     wait on average longer, the same or shorter before the monkey
     will have typed ‘abracadabra’ or ‘abcdefghijk’ (i.e. a string
     with an equal amount of characters)?'
     
     See:
       http://douweosinga.com/projects/abracadabra
"""

import random

aa_win = 0
ab_win = 0
aa_first = 0.0
ab_first = 0.0
count = 0

for k in range(200):
  for i in range(1000):
    t = ''.join(['abcdef'[random.randint(0,119) / 20] for j in range(1000)])
    aa = t.find('aa')
    if aa == -1:
      continue
    ab = t.find('ab')
    if ab == -1:
      continue
    if aa < ab:
      aa_win += 1
    elif aa > ab:
      ab_win += 1
    count += 1
    aa_first += aa
    ab_first += ab

  print '-'
  t = (aa_win + ab_win) / 100.0
  print 'aa wins: %4.3f%% len: %4.3f' % (aa_win / t, aa_first / count)
  print 'aa wins: %4.3f%% len: %4.3f' % (ab_win / t, ab_first / count)
