# Java Spiral Matrix

Published: Feb 9, 2019

Last updated: Feb 9, 2019

## Writing the tests

```.css-e69dqy{position:relative;z-index:0;}.css-qq5p7o{padding:var(--chakra-space-5);border-radius:8px;margin-top:var(--chakra-space-8);margin-bottom:var(--chakra-space-8);background:#011627;-webkit-padding-start:0px;padding-inline-start:0px;-webkit-padding-end:0px;padding-inline-end:0px;overflow:hidden;}// 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

```// 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 Visibuild.