Back to home

Test FileSpiral MatrixRunning Tests
PHP Spiral Matrix main image

PHP Spiral Matrix

This expects an installation on the system of phpunit.

Test File

Create php-spiral-matrix_test.php:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 <?php require "php-spiral-matrix.php"; class PhpSpiralMatrixTest extends PHPUnit\Framework\TestCase { public function testTwoByTwoSprialMatrix() { $size = 2; $expected = array( array(1, 2), array(4, 3) ); $this->assertEquals($expected, sprialMatrix($size)); } public function testThreeByThreeSprialMatrix() { $size = 3; $expected = array( array(1, 2, 3), array(8, 9, 4), array(7, 6, 5) ); $this->assertEquals($expected, sprialMatrix($size)); } }

Spiral Matrix

Create binary-search-tree.php:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 <?php function sprialMatrix($size) { $base = array_fill(0, $size, 0); $mat = array_fill(0, $size, $base); $count = 1; $startCol = 0; $endCol = $size - 1; $startRow = 0; $endRow = $size - 1; while ($startCol <= $endCol && $startRow <= $endRow) { // top row for ($i = $startCol; $i <= $endCol; $i++) { $mat[$startRow][$i] = $count; $count++; } $startRow++; // right col for ($i = $startRow; $i <= $endRow; $i++) { $mat[$i][$endCol] = $count; $count++; } $endCol--; // bottom row for ($i = $endCol; $i >= $startCol; $i--) { $mat[$endRow][$i] = $count; $count++; } $endRow--; // left col for ($i = $endRow; $i >= $startRow; $i--) { $mat[$i][$startCol] = $count; $count++; } $startCol++; } return $mat; }

Running Tests

Change into directory and run phpunit.phar php-spiral-matrix_test.php.

Dennis O'Keeffe

@dennisokeeffe92
  • Melbourne, Australia

Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
I am currently working on workingoutloud.dev, Den Dribbles and LandPad .

Related articles


1,200+ PEOPLE ALREADY JOINED ❤️️

Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.