Tuesday, September 17, 2019

UVa 10114 - Loansome Car Buyer

// UVa 10114 - Loansome Car Buyer

program UVa10114;

type
    DeprecationRecord = record
        month : integer;
        percentage : real;
    end;

var
    durationInMonths : integer;
    downPayment, loanAmount : real;
    numberOfDepreciationRecords : integer;
    depreciation : array[1..102] of DeprecationRecord;
    sol, i : integer;

function completeMonthsBeforeBorrowerOwnsLessThanCarIsWorth : integer;
var
    monthsPassed : integer;
    carWorth : real;
    borrowerOwns : real;
    monthlyPayment : real;
begin
    carWorth := downPayment + loanAmount;
    borrowerOwns := loanAmount;
    monthlyPayment := loanAmount / durationInMonths;
    
    carWorth := carWorth - carWorth * depreciation[1].percentage;
    monthsPassed := 0;
    
    for i:= 2 to numberOfDepreciationRecords do begin
        if (borrowerOwns < carWorth) then break;
        while (monthsPassed + 1 < depreciation[i].month) do begin
            borrowerOwns := borrowerOwns - monthlyPayment;
            carWorth := carWorth - (carWorth * depreciation[i-1].percentage);
            monthsPassed := monthsPassed + 1;
            if (borrowerOwns < carWorth) then break;
        end;
        if (borrowerOwns < carWorth) then break;
    end;
    completeMonthsBeforeBorrowerOwnsLessThanCarIsWorth := monthsPassed;
end;

begin
    while not EOF() do begin
        readln(durationInMonths, downPayment, loanAmount, numberOfDepreciationRecords);
        if (durationInMonths < 0) then break;
        for i:= 1 to numberOfDepreciationRecords do begin
            readln(depreciation[i].month, depreciation[i].percentage);
        end;
        numberOfDepreciationRecords := numberOfDepreciationRecords + 1;
        depreciation[numberOfDepreciationRecords].month := durationInMonths + 1;
        depreciation[numberOfDepreciationRecords].percentage := 0;
        sol := completeMonthsBeforeBorrowerOwnsLessThanCarIsWorth;
        write(sol,' ');
        if sol = 1 then writeln('month') else writeln('months');
    end;
end.

No comments:

Post a Comment