Back to home

Writing the testsWriting the solution
Java Spiral Matrix main image

Java Spiral Matrix

Writing the tests

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 // src/test/java/SpiralMatrixTest.java import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertArrayEquals; public class SpiralMatrixTest { @Test public void testTwoByTwo() { int[][] expected = { { 1, 2 }, { 4, 3 } }; assertArrayEquals(new SpiralMatrix().gen(2), expected); } @Test public void testThreeByThree() { int[][] expected = { { 1, 2, 3 }, { 8, 9, 4 }, { 7, 6, 5 } }; assertArrayEquals(new SpiralMatrix().gen(3), expected); } }

Writing the solution

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 47 48 49 // src/main/java/SpiralMatrix.java import java.util.Arrays; class SpiralMatrix { int[][] gen(int size) { int[][] expected = new int[size][size]; int count = 1; int colStart = 0; int colEnd = size - 1; int rowStart = 0; int rowEnd = size - 1; while (colStart <= colEnd && rowStart <= rowEnd) { // top row for (int i = colStart; i <= colEnd; i++) { expected[rowStart][i] = count; count++; } rowStart++; // far column for (int i = rowStart; i <= rowEnd; i++) { expected[i][colEnd] = count; count++; } colEnd--; // bottom row for (int i = colEnd; i >= colStart; i--) { expected[rowEnd][i] = count; count++; } rowEnd--; // start col for (int i = rowEnd; i >= rowStart; i--) { expected[i][colStart] = count; count++; } colStart++; } for (int i = 0; i < size; i++) { System.out.println(Arrays.toString(expected[i])); } return expected; } }

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.