%********o*********o*********o*********o*********o*********o*********o*********
% LaGuardia.m-- matlab program to simulate the scheduling of landings and
% takeoffs at an airport.  It is problem 28 on page 511 of the Nyhoff &
% Leestma fortran book.
%---------------------
% Author:   Bob Harris
% Class:    CMPSC 201F
% Section:  1234
% Date Due: 24 Nov 2003
%********o*********o*********o*********o*********o*********o*********o*********

rand('state',16802)

% set up mapping strings to convert a runway state into an output string

laString      = ['--'; 'LA'];
landingString = ['-- -- --'; '-- -- LC'; '-- LP --'; 'LB -- --'];
taString      = ['--'; 'TA'];
takeoffString = ['-- --'; '-- TC'; 'TB --'];

%initialize the state of things

runway  = 0;            % runway clear (neg => landing, pos => takeoff)
waiting = [0 0];        % no planes waiting in either queue
sumWaiting = [0 0];     % this array will be the sum of the queue lengths
countRequests = [0 0];  % this array will count the number of each type plane

h = 0;
m = 0;
duration = 24*60;

for t=1:duration

    % generate requests

    requests = rand(1,2) < 8/60;
    waiting  = waiting + requests;
    countRequests = countRequests + requests;

    % advance runway state

    if (runway < 0)
        runway = runway + 1;
    elseif (runway > 0)
        runway = runway - 1;
    end
    
    % satisfy waiting planes

    if (runway == 0)
        if (waiting(1) > 0)
            waiting(1) = waiting(1)-1;
            runway = -3;
        elseif (waiting(2) > 0)
            waiting(2) = waiting(2)-1;
            runway = 2;
        end
    end

    sumWaiting = sumWaiting + waiting;

    % print current state

    if ((h == 23) & (m==00))
        fprintf (1,'----------\n');
    end

    if ((h == 0) | (h==23))
        landing = 1;
        takeoff = 1;
        if (runway < 0)
            landing = 1 - runway;
        elseif (runway > 0)
            takeoff = 1 + runway;
        end 

        fprintf (1,' %02d%02d',h,m);                 % time
        fprintf (1,' %s',laString(1+requests(1),:)); % landing request
        fprintf (1,' %s',landingString(landing,:));  % landing state
        fprintf (1,' %s',taString(1+requests(2),:)); % takeoff request
        fprintf (1,' %s',takeoffString(takeoff,:));  % takeoff state
        fprintf (1,' %d %d',waiting);                % queues
        fprintf (1,'\n');                            % end of line
    end

    % advance time

    [h m] = nexttime (h,m);

end

fprintf (1,'                      landing  takeoff\n');
fprintf (1,'planes:               %8d %8d\n',    countRequests);
fprintf (1,'average queue length: %8.6f %8.6f\n',sumWaiting ./ duration);
fprintf (1,'average waiting time: %8.6f %8.6f\n',sumWaiting ./ countRequests);


