User:Thebigh/mysandbox

From Rosetta Code
Revision as of 19:18, 15 November 2021 by Thebigh (talk | contribs) (more)

An evil wizard has trapped you in the stairwell of his castle. Your only hope of escape is to run up all 100 steps to reach the top, and you can run one step per second. Unfortunately the wizard uses magic to lengthen the staircase by five steps per second. The new steps are inserted randomly between existing steps, so if you're lucky some of them might be beneath you and not ahead of you.

Can you escape, or are you doomed to run up an ever-lengthening staircase forever?

Write a program to simulate your escape attempt. How are you doing after ten minutes? For every second between 600 and 609 seconds inclusive print the number of steps behind you and the number still ahead of you.

If you escaped, run 10,000 tests and print the average time taken and the average final length of the staircase.

header|FreeBASIC

<lang freebasic> randomize timer dim as uinteger steps_behind = 0, stairs_length = 100, seconds, j dim as uinteger seconds_tot, steps_tot print "Seconds", "steps behind", "steps ahead" for trial as uinteger = 1 to 10000 'We'll have the runner try this 10000 times

   steps_behind = 0                      'runner starts at the bottom
   seconds = 0                           'reset time taken
   stairs_length = 100                   'Staircase has 100 steps
   while steps_behind < stairs_length    'if the runner hasn't reached the top
       steps_behind += 1                 'go up one step
       for j = 1 to 5                    'The evil wizard conjures another five steps
           if int(rnd*stairs_length) < steps_behind then steps_behind += 1
                                         'there's a chance that a new step will be behind you
           stairs_length += 1            'but either way the staircase is one step longer
       next j
       seconds += 1                      'that all took one second
       if trial = 1  and seconds >599 and seconds < 610  then print seconds, steps_behind, stairs_length - steps_behind
                                         'for the first attempt, see how the runner is doing after ten minutes
   wend
   seconds_tot += seconds                'if the runner escaped, track the time taken and the length of the stairs
   steps_tot += stairs_length

next trial

print "Average time taken: ";seconds_tot/10000; " seconds." print "Average final staircase length: ";steps_tot/10000; " steps." 'if you noticed that last number is about 100*exp(5), that's no coincidence</lang>

Output:

Seconds steps behind steps ahead 600 2032 1068 601 2038 1067 602 2042 1068 603 2045 1070 604 2048 1072 605 2053 1072 606 2055 1075 607 2060 1075 608 2064 1076 609 2068 1077 Average time taken: 2921.9457 seconds. Average final staircase length: 14709.7285 steps.