DEV Community

Discussion on: Spiral Matrices with Julia

Collapse
 
jaheim profile image
Skyjaheim2 • Edited

An alternative solution using recursion:

def main():
    n = 4
    Matrix = generateEmptyMatrix(n)

    generateMatrix(Matrix, n, 0, 0, n, n)

def generateMatrix(matrix, dimension, startRow, startColumn, endRow, endColumn, counter=10, delta=0):
    if dimension == 1:
        matrix[startRow][startColumn] = counter
        return displayMatrix(matrix)
    if dimension == 2:
        # GENERATE FIRST ROW
        for i in range(startRow, endRow):
            matrix[startRow][i] = counter
            counter += 1
        # GENERATE LAST ROW
        for i in range(2):
            matrix[startRow+1][startRow+1 -i] = counter
            counter += 1
        return displayMatrix(matrix)
    else:
        # GENERATE FIRST ROW
        for i in range(startRow, endRow):
            matrix[startRow][i] = counter
            counter += 1
        # GENERATE LAST COLUMN
        for i in range(startColumn+1, endColumn):
            matrix[i][endColumn - 1] = counter
            counter += 1
        # GENERATE LAST ROW
        for i in range(startRow + 1, endRow):
            matrix[endRow - 1][endColumn - 1 - i + delta] = counter
            counter += 1
        # GENERATE FIRST COLUMN
        for i in range(startRow + 1, endColumn - 1):
            matrix[endRow - 1 - i + delta][startColumn] = counter
            counter += 1
        return generateMatrix(matrix, dimension - 2, startRow + 1, startColumn + 1, endRow - 1, endColumn - 1, counter, delta + 1)
Enter fullscreen mode Exit fullscreen mode

Output when n = 4 (I started my counter at 10 instead of 1):

[10, 11, 12, 13]
[21, 22, 23, 14]
[20, 25, 24, 15]
[19, 18, 17, 16]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
leadersheir_ profile image
Warisul Imam

If it's okay with you, may I add it to the article (with credits to you for the section, of course) so that people can have two different ways of solving the problem in the same place?

Collapse
 
jaheim profile image
Skyjaheim2

Yes, it's ok with me

Thread Thread
 
leadersheir_ profile image
Warisul Imam

Could you check your DM, please?