FunctionRacerProblemsRace

Fare Card With Free Transfers

EasyClassesPython, JavaScript, TypeScript, Java, C++

Implement a class FareCard for a transit card. A ride costs fare, but one tap within window minutes after a paid tap is a free transfer. Write these methods:

- FareCard(fare, window) starts with a balance of 0.
- add_value(amount) adds amount to the balance and returns the new balance.
- tap(now) is a tap at minute now.
- If the last paid tap was at minute p, now - p <= window, and no free transfer has been used since that paid tap, this tap is a free transfer: it returns 0.
- Otherwise the tap must be paid. If the balance is at least fare, fare is taken from the balance, this tap becomes the last paid tap, and it returns fare. If not, the tap is refused: nothing changes and it returns -1.
- read_balance() returns the balance.
- count_rides() returns how many taps were let through, paid or free.

now never decreases from one call to the next. The tests call the methods in sequence and compare every return value. The expected list holds null for the constructor.

Example 1

FareCard(3, 90)
tap(0) returns -1
add_value(7) returns 7
tap(10) returns 3
tap(100) returns 0
tap(101) returns 3
tap(200) returns -1
read_balance() returns 1
count_rides() returns 3

The tap at minute 100 is exactly 90 minutes after the paid tap at 10, so it is free. The next tap has to pay because that transfer is used up, and the last tap is refused because only 1 is left.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Classes problems