3484. Design Spreadsheet #2192
-
Topics: A spreadsheet is a grid with 26 columns (labeled from Implement the
Note: If Example 1:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to design a spreadsheet class that supports setting cell values, resetting cell values, and evaluating formulas that sum two operands, which can be either cell references or integers. The key challenge is efficiently managing cell values and parsing formulas to compute the sum correctly. Approach
Let's implement this solution in PHP: 3484. Design Spreadsheet <?php
class Spreadsheet {
private $rows;
private $cells;
/**
* @param Integer $rows
*/
function __construct($rows) {
$this->rows = $rows;
$this->cells = [];
}
/**
* @param String $cell
* @param Integer $value
* @return NULL
*/
function setCell($cell, $value) {
$this->cells[$cell] = $value;
}
/**
* @param String $cell
* @return NULL
*/
function resetCell($cell) {
$this->cells[$cell] = 0;
}
/**
* @param String $formula
* @return Integer
*/
function getValue($formula) {
$expr = substr($formula, 1);
$parts = explode('+', $expr);
$sum = 0;
foreach ($parts as $part) {
if (preg_match('/^[A-Z]\d+$/', $part)) {
if (isset($this->cells[$part])) {
$sum += $this->cells[$part];
} else {
$sum += 0;
}
} else {
$sum += (int)$part;
}
}
return $sum;
}
}
/**
* Your Spreadsheet object will be instantiated and called as such:
* $obj = Spreadsheet($rows);
* $obj->setCell($cell, $value);
* $obj->resetCell($cell);
* $ret_3 = $obj->getValue($formula);
*/
// Test cases
$spreadsheet = new Spreadsheet(3);
echo $spreadsheet->getValue("=5+7") . PHP_EOL; // 12
$spreadsheet->setCell("A1", 10);
echo $spreadsheet->getValue("=A1+6") . PHP_EOL; // 16
$spreadsheet->setCell("B2", 15);
echo $spreadsheet->getValue("=A1+B2") . PHP_EOL; // 25
$spreadsheet->resetCell("A1");
echo $spreadsheet->getValue("=A1+B2") . PHP_EOL; // 15
?> Explanation:
This approach efficiently manages cell values and evaluates formulas by leveraging regular expressions to distinguish between cell references and integers, ensuring correct summation based on the current state of the spreadsheet. The solution handles all constraints and edge cases as specified in the problem. |
Beta Was this translation helpful? Give feedback.
We need to design a spreadsheet class that supports setting cell values, resetting cell values, and evaluating formulas that sum two operands, which can be either cell references or integers. The key challenge is efficiently managing cell values and parsing formulas to compute the sum correctly.
Approach