I just solved a problem from leetcode that is faster than 28.42% of the PHP codes, so the main review target is not the performance or alternative ways to solve this problem. I wrote the code thinking about DX, how readable and clear my code is, but currently I don't have anybody to judge my code.
A particularity of the algorithm is that I tried to use hash-maps as much as I could, even though I'm aware that I didn't give too much attention to designing the hash key, to be honest.
I would like to hear your ideas how I could improve the way I name my variables and separate the responsibilities through the functions.
Thanks :)
Also, any other advice is very welcome!
Here is my algorithm:
class Solution {
public function rotateBoard($board) {
$newBoard = [];
$boardWidth = $board[0];
foreach($boardWidth as $column=>$value) {
$newRow = [];
foreach($board as $row) {
$digit = $row[$column];
array_push($newRow, $digit);
}
array_push($newBoard, $newRow);
}
return $newBoard;
}
public function squashBox($board) {
$flatBoxes = [];
$boxIndexes = [0, 3, 6];
$boardLength = count($board[0]);
$boxRows = [];
for($start = 0; $start < $boardLength; $start += 3) {
for($row = 0; $row < $boardLength; $row += 1) {
$boxWidth = 3;
$boxRow = array_slice($board[$row], $start, $boxWidth);
$boxRows[] = $boxRow;
}
}
$boxesList = [];
for($start = 0; $start < count($boxRows); $start += 3) {
$end = 3;
$box = array_slice($boxRows, $start, $end);
$boxesList[] = $box;
}
$boxes = [];
for($boxIndex = 0; $boxIndex < count($boxesList); $boxIndex += 1) {
$boxList = $boxesList[$boxIndex];
$row = [];
for($box = 0; $box < count($boxList); $box += 1) {
$choosenBox = $boxList[$box];
for($index = 0; $index < count($choosenBox); $index += 1) {
$digit = $choosenBox[$index];
array_push($row, $digit);
}
}
array_push($boxes, $row);
}
return $boxes;
}
public function validateRows($board) {
foreach($board as $row) {
$map = [];
foreach($row as $digit) {
if($map[$digit] === true) {
return false;
} elseif($digit !== '.') {
$map[$digit] = true;
}
}
}
return true;
}
public function validateColumns($board) {
$rotatedBoard = $this->rotateBoard($board);
return $this->validateRows($rotatedBoard);
}
public function validateBoxes($board) {
$flatBoxes = $this->squashBox($board);
return $this->validateRows($flatBoxes);
}
function isValidSudoku($board) {
return $this->validateBoxes($board) && $this->validateColumns($board) && $this->validateRows($board);
}
}
And here is a input sample:
[["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]]