Tray of Weights
Implement a class WeightTray for a stack of weights on a tray: weights are put on top of each other, and usually the top one is taken off first. But sometimes the heaviest weight is pulled out from wherever it sits. Write these methods:
WeightTray()starts with an empty tray.put(weight)puts a weight on top.read_top()returns the top weight, or-1if the tray is empty.take_top()removes the top weight and returns it, or returns-1if the tray is empty.get_heaviest()returns the heaviest weight on the tray, or-1if the tray is empty.take_heaviest()removes the heaviest weight and returns it, or returns-1if the tray is empty. If several weights are equally heavy, the one nearest the top goes. The weights above it keep their order.
The tests call the methods in sequence and compare every return value. The expected list holds null for the constructor.
Example 1
WeightTray()
put(5)
put(2)
put(5)
take_heaviest() returns 5
read_top() returns 2
get_heaviest() returns 5
take_heaviest() returns 5
take_top() returns 2
take_top() returns -1
The tray holds 5, 2, 5 from the bottom up. Taking the heaviest removes the upper 5, which leaves 2 on top. The next heaviest is the other 5, and after that only the 2 is left.
Constraints
1 <= weight <= 100- Each test makes
1to40method calls after the constructor.
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Classes problems
- Two-Tier CacheHard
- Bank Account Without OverdraftsBeginner
- Grid With Row and Column AddsBeginner
- Guest Book SignaturesBeginner
- Odometer With a Trip MeterBeginner
- Panel of Light SwitchesBeginner
- Rectangle on the TableBeginner
- Scoreboard by RoundsBeginner