% Code Interview: Two-Rocket Altitude Race (to ~100 km)
% Concepts: for, while, if/elseif, comparisons, compound logic (&, |), switch

N = 1000000;                    % number of trials
results = zeros(N,1);       % 0=tie, 1=A wins, 2=B wins

ALT_TARGET = 100;           % target altitude in km
MAX_TURNS = 50;             % turn cap (safety stop)

for n = 1:N
    hA = 0; hB = 0;         % altitudes in km
    fuelA = 20; fuelB = 20; % fuel units
    turn = 0;

    while ((hA < ALT_TARGET) && (hB < ALT_TARGET)) && (turn < MAX_TURNS)
        turn = turn + 1;

        % baseline climb per step if fuel left
        if fuelA > 0
            hA = hA + randi(5);  % random climb step
            fuelA = fuelA - 1;
        end
        if fuelB > 0
            hB = hB + randi(5);
            fuelB = fuelB - 1;
        end

        % random event each turn
        evt = randi(6);
        switch evt
            case 1  % turbulence knocks back rocket A
                hA = hA - 3;
            case 2  % turbulence knocks back rocket B
                hB = hB - 3;
            case 3  % boost if BOTH rockets still have fuel
                if (fuelA > 0 & fuelB > 0)    
                    hA = hA + 2; hB = hB + 2;
                end
            case 4  % lucky break for lead rocket
                if hA ~= hB
                    if hA > hB
                        hA = hA + 3;
                    elseif hB > hA
                        hB = hB + 3;
                    else
                        hA = hA + 1;
                        hB = hB + 1;
                    end
                end
            otherwise
                % no event
        end
    end

    % outcome
    if (hA >= ALT_TARGET) && (hB >= ALT_TARGET)
        results(n) = 0;     % tie
    elseif hA > hB
        results(n) = 1;     % A wins
    else
        results(n) = 2;     % B wins
    end
end

% summary histogram
histogram(results)
xticks(0:2)
xticklabels(["Ties" "Rocket A Wins" "Rocket B Wins"])
title('Simple Rocket Climb Race Outcomes')
xlabel('Outcome'); ylabel('Count')
