Spreadsheet Sums Without Cycles
Implement a class SumSheet for a spreadsheet in which a cell holds either a number or a formula that adds up other cells. Cells are named like "B2", and a cell that was never set holds the number 0. Write these methods:
SumSheet()starts with every cell empty.set_number(cell, value)makescellhold the numbervalue, replacing any formula it had.set_sum(cell, refs)makescellhold the formula that adds up the cells inrefs; a cell listed twice counts twice. If the formula would makecelldepend on itself, directly or through other formulas, it is refused: nothing changes and it returnsfalse. Otherwise it replaces whatevercellheld and returnstrue.get_value(cell)returns the value ofcell: its number, or the sum of the values of the cells in its formula.count_dependents(cell)returns how many other cells hold a formula whose value depends oncell, directly or through other formulas.
The tests call the methods in sequence and compare every return value. The expected list holds null for the constructor.
Example 1
SumSheet()
set_number("A1", 5)
set_number("A2", 7)
set_sum("B1", ["A1","A2","A1"]) returns true
get_value("B1") returns 17
set_sum("C1", ["B1","A2"]) returns true
get_value("C1") returns 24
set_sum("A1", ["C1"]) returns false
count_dependents("A1") returns 2
set_number("A2", 1)
get_value("C1") returns 12
B1 counts A1 twice, so it is 5 + 7 + 5 = 17. Making A1 add up C1 is refused, because C1 already depends on A1 through B1. Changing A2 to 1 flows through B1 into C1.
Constraints
- cell names are
"A1"to"C3": a letter fromAtoCand a digit from1to3 -100 <= value <= 1001 <= len(refs) <= 3- 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
- Tiny DiskHard
- Tray of WeightsHard
- 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