Commit 3d9dbe56 by Fokion Zervoudakis

### Update spiral algorithm and add unit tests.

parent 8013f68e
 ... ... @@ -6,27 +6,33 @@ import java.util.List; class Spiral { List clockwise(int[][] M) { List L = new ArrayList<>(); if (M.length == 0) { return L; } int t = 0, b = M.length - 1, l = 0, r = M[0].length - 1; while (true) { for (int i = l; i <= r; i++) L.add(M[t][i]); if (++t > b) break; for (int i = t; i <= b; i++) L.add(M[i][r]); if (l > --r) break; for (int i = r; i >= l; i--) L.add(M[b][i]); if (t > --b) break; for (int i = b; i >= t; i--) L.add(M[i][l]); if (++l > r) break; int m = M.length, n = M[0].length; int row = 0, col = 0; while (row < m && col < n) { for (int i = col; i < n; i++) { L.add(M[row][i]); } row++; for (int i = row; i < m; i++) { L.add(M[i][n - 1]); } n--; if (row < m) { for (int i = n - 1; i >= col; i--) { L.add(M[m - 1][i]); } m--; } if (col < n) { for (int i = m - 1; i >= row; i--) { L.add(M[i][col]); } col++; } } return L; } }
 ... ... @@ -14,7 +14,18 @@ class SpiralTest { } @Test void itTraversesASquareMatrixClockwise() { void itTraversesASmallSquareMatrixClockwise() { var M = new int[][] { { 1, 2 }, { 3, 4 } }; var expected = "[1, 2, 4, 3]"; var actual = spiral.clockwise(M).toString(); assertEquals(expected, actual); } @Test void itTraversesALargeSquareMatrixClockwise() { var M = new int[][] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, ... ... @@ -27,12 +38,24 @@ class SpiralTest { } @Test void itTraversesARectangularMatrixClockwise() { void itTraversesASmallRectangularMatrixClockwise() { var M = new int[][] { { 1, 2, 3 }, { 4, 5, 6 } }; var expected = "[1, 2, 3, 6, 5, 4]"; var actual = spiral.clockwise(M).toString(); assertEquals(expected, actual); } @Test void itTraversesALargeRectangularMatrixClockwise() { var M = new int[][] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } { 5, 6, 7, 8 }, { 9, 10, 11, 12 } }; var expected = "[1, 2, 3, 4, 8, 7, 6, 5]"; var expected = "[1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]"; var actual = spiral.clockwise(M).toString(); assertEquals(expected, actual); } ... ...
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment