lots of exercises in java... from https://github.com/exercism/java

SpiralMatrixBuilder.java 840B

123456789101112131415161718192021222324252627282930
  1. class SpiralMatrixBuilder {
  2. int[][] buildMatrixOfSize(int size) {
  3. if (size == 0) {
  4. return new int[][]{};
  5. }
  6. int[][] result = new int[size][size];
  7. int entryCount = (int) Math.pow(size, 2.0);
  8. Coordinate coord = new Coordinate(0, 0);
  9. Direction direction = Direction.RIGHT;
  10. for (int i = 0; i < entryCount; i++) {
  11. result[coord.getY()][coord.getX()] = i + 1;
  12. Coordinate maybeNextCoord = coord.step(direction);
  13. if (maybeNextCoord.isWithinGridOfSize(size) && result[maybeNextCoord.getY()][maybeNextCoord.getX()] == 0) {
  14. coord = maybeNextCoord;
  15. } else {
  16. direction = direction.turnRight();
  17. coord = coord.step(direction);
  18. }
  19. }
  20. return result;
  21. }
  22. }