Design a simplified spreadsheet that can store constant integers, evaluate addition formulas, print a range of rows, and detect circular dependencies. The grid has a configurable but constant number of columns C, set once when the spreadsheet is created. Rows are added dynamically; referencing a row beyond the current size automatically extends the sheet. All row and column indices are 1-based.
You need to implement the following methods:
set_cell(row, col, value)Store an integer constant in cell (row, col). This overwrites any previous content, whether it was a constant or a formula.
get_cell(row, col) -> int | ERRORReturn the evaluated value of the cell. If the cell contains a constant, that integer is returned. If it holds an ADD formula, compute the sum of the two referenced cells (which may themselves be formulas). If evaluation triggers a dependency cycle, return ERROR (or throw an exception – the exact error signalling is up to you, as long as the caller can detect it).
print_n_rows(n) -> stringPrint the first n rows. For each row, output exactly C evaluated values from column 1 to C, separated by single spaces. Any cell that was never set has a value of 0. Rows are separated by newline characters. The returned string must contain the rows as described.
ADDProvide a method to set a cell to the sum of two other cells:
set_add_formula(target_row, target_col, a_row, a_col, b_row, b_col)
This makes the target cell equal to cell(a_row, a_col) + cell(b_row, b_col). The formula is evaluated on the fly whenever get_cell or print_n_rows reads the target. You may cache computed values, but correctness is mandatory: any change to a dependency must be reflected in subsequent evaluations.
If cells depend on each other in a cycle (directly or indirectly), any attempt to evaluate a cell involved in the cycle must detect it and produce an ERROR. For example, a cycle exists when A depends on B and B depends on A.
C is fixed at initialization.set_cell, set_add_formula, get_cell, and print_n_rows calls efficiently.Let C = 3.
set_cell(1, 1, 10)set_cell(1, 2, 5)set_add_formula(1, 3, 1, 1, 1, 2) # cell(1,3) = 10 + 5 = 15print_n_rows(1) outputs:
10 5 15
Now suppose you then call set_add_formula(1, 1, 1, 3, 1, 2), making cell (1,1) a formula that depends on (1,3), which already depends on (1,1). This introduces a cycle. Any subsequent get_cell or print that touches these cells should return ERROR.