کد
<?php
namespace Techanic\CS\DS\Linear\Vector;
use Exception;
abstract class AbstractTwoDimArray
{
/**
*
* @var array
*/
private /*array*/ $_size = [0, 0];
/**
*
* @var array
*/
private /*array*/ $_values = [];
protected abstract function getValueType() : string;
protected abstract function getDefaultValue();
public function __construct(int $rows, int $cols)
{
if ($rows < 0)
throw new Exception('rows must be positive number.');
if ($cols < 0)
throw new Exception('cols must be positive number.');
$this->_size = [$rows, $cols];
$defaultValue = $this->getDefaultValue();
if (gettype($defaultValue) != $this->getValueType())
throw new Exception('Return type of the getDefaultValue() does not match getValueType().');
for ($row = 0; $row < $this->_size[0]; $row++) {
for ($col = 0; $col < $this->_size[1]; $col++)
$this->_values[$row][$col] = $defaultValue;
}
}
public function Size(): array
{
return $this->_size;
}
public function Set(int $row, int $col, $value)
{
if ($row < 0 || $row >= $this->_size[0])
throw new Exception('The row index must be in the range (0, ' . ($this->_size[0] -1) . ')');
if ($col < 0 || $col >= $this->_size[1])
throw new Exception('The col index must be in the range (0, ' . ($this->_size[1] -1) . ')');
if (gettype($value) != $this->getValueType())
throw new Exception('The value must be of type ' . $this->getValueType());
$this->_values[$row][$col] = $value;
}
public function Get(int $row, int $col)
{
if ($row < 0 || $row >= $this->_size[0])
throw new Exception('The row index must be in the range (0, ' . ($this->_size[0] -1) . ')');
if ($col < 0 || $col >= $this->_size[1])
throw new Exception('The col index must be in the range (0, ' . ($this->_size[1] -1) . ')');
return $this->_values[$row][$col];
}
}
class IntTwoDimArray extends AbstractTwoDimArray
{
protected function getValueType() : string
{
return gettype(0);
}
protected function getDefaultValue()
{
return 0;
}
}
$rows = 5;
$cols = 5;
$intMatrix = new IntTwoDimArray($rows, $cols);
for ($row = 0; $row < $intMatrix->Size()[0]; $row++) {
for ($col = 0; $col < $intMatrix->Size()[1]; $col++)
echo $intMatrix->Get($row, $col) . ' ';
echo PHP_EOL;
}
echo PHP_EOL;
for ($row = 0; $row < $intMatrix->Size()[0]; $row++) {
for ($col = 0; $col < $intMatrix->Size()[1]; $col++)
$intMatrix->Set($row, $col, $row + $col);
}
for ($row = 0; $row < $intMatrix->Size()[0]; $row++) {
for ($col = 0; $col < $intMatrix->Size()[1]; $col++)
echo $intMatrix->Get($row, $col) . ' ';
echo PHP_EOL;
}
echo PHP_EOL;