javamatrixzigzag

Print elements of a matrix in diagonal stripes


I want to generate a matrix with consecutive numbers starting from 1, in this form zig zag matrix

public static int[][] Zig_Zag(final int size) {
        int[][] data = new int[size][size];
        int i = 1;
        int j = 1;
        for (int element = 0; element < size * size; element++) {
            data[i - 1][j - 1] = element;
            if ((i + j) % 2 == 0) { // Even stripes if (j < size) j++; else i+=
                                    // 2; if (i > 1) i--; } else { // Odd
                                    // stripes if (i < size) i++; else j+= 2; if
                                    // (j > 1) j--; } } return data; }
            }
        }
        return data;
    }

Can anybody help?


Solution

  • Try this

    public static int[][] Zig_Zag(int size) {
        int[][] a = new int[size][size];
        int n = 1;
        for (int r = size, c = 0; r >= 0; --r)
            for (int i = r, j = c; i < size; ++i, ++j)
                a[i][j] = n++;
        for (int r = 0, c = 1; c < size; ++c)
            for (int i = r, j = c; j < size; ++i, ++j)
                a[i][j] = n++;
        return a;
    }
    

    and

    int[][] a = Zig_Zag(4);
    for (int[] r : a)
        System.out.println(Arrays.toString(r));
    

    result:

    [7, 11, 14, 16]
    [4, 8, 12, 15]
    [2, 5, 9, 13]
    [1, 3, 6, 10]