Contents

Spiralizing integers (with.Java)

   Dec 5, 2023     3 min read

This is a recap of the ā€œArrange integers in a spiralā€ problem.

Weā€™re going to learn by solving coding test problems, reflecting on the problems we solved, and exploring other ways to solve them.

Letā€™s start with the problem

Problem

A positive integer n is given as a parameter.

Write a solution function that returns a two-dimensional array containing the integers 1 through n2 in an n Ɨ n array, placed in a clockwise spiral from index [0][0].

Example input and output

nresultĀ 
4[[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]Ā 
5[[1, 2, 3, 4, 5], [16, 17, 18, 19, 6], [15, 24, 25, 20, 7], [14, 23, 22, 21, 8], [13, 12, 11, 10, 9]]}

My solution to the ### problem

public class Solution {
    public int[][] solution(int n) {
        int[][] result = new int[n][n];

        int num = 1;
        int rowStart = 0, rowEnd = n - 1;
        int colStart = 0, colEnd = n - 1;

        while (num <= n * n) {
            for (int i = colStart; i <= colEnd; i++) {
                result[rowStart][i] = num++;
            }
            rowStart++;
            for (int i = rowStart; i <= rowEnd; i++) {
                result[i][colEnd] = num++;
            }
            colEnd--;
            for (int i = colEnd; i >= colStart; i--) {
                result[rowEnd][i] = num++;
            }
            rowEnd--;
            for (int i = rowEnd; i >= rowStart; i--) {
                result[i][colStart] = num++;
            }
            } colStart++;
    }

} return result;

solution

int[][] result = new int[n][n];: Create a two-dimensional array result of size n x n.

int num = 1;: Initialize the number.

int rowStart = 0, rowEnd = n - 1; and int colStart = 0, colEnd = n - 1;: Initialize the start and end indices of the rows and columns.

while (num <= n * n): iterates while the number num is less than or equal to n x n.

for (int i = colStart; i <= colEnd; i++) : Fills in the numbers in the top row of the current matrix, moving from left to right.

Store num in result[rowStart][i] and increment num.

rowStart++;: After filling the top row, move to the next row.

Now fill the numbers in the right column, moving from top to bottom, then the left row, moving from right to left, then the bottom row, moving from top to bottom.

At each step, num is incremented by 1 and the start and end indices of the rows and columns are adjusted.

return result;: Returns a two-dimensional array result with all elements filled with numbers.

This code uses an efficient spiral pattern to create a two-dimensional array and populate it with numbers from 1 to n x n.