spiralgo / algorithms

We voluntarily solve algorithm problems on this repo.
24 stars 7 forks source link

631. Design Excel Sum Formula #389

Closed ErdemT09 closed 3 years ago

ErdemT09 commented 3 years ago

Resolves: #242

Algorithm:

When calculating the value of each cell, there are 2 possibilities:

  1. The cell only has a value.
  2. The cell points to a collection of cells and/or rectangles.

set() method updates the value of some cell to an integer. sum() method updates the value of some cell to a collection of cell names.

In order to get the value of summed cells, 2. type of cells, we try to calculate the value of each cell/rectangle they point at. Let's say: D4 = [B1:C2, A2]. In order to calculate D4, we need to calculate The range B1:C2. This range might also contain references to other ranges, for example a case might be: B2 = [A1:A3]. For calculating this, we also need to sum this range. This yields a recursive method where we calculate the value of each cell each time by calculating the ranges they point to. When values are updated, the structure recalculates such values each time again, so we don't have to worry about updating something like the prefix sum etc.

In implementation, cells are Objects that are either Integer, pure value, or String[], reference to other cells by name, which gets parsed by the calculate() method.