Search code examples
javaarraysstringsortingdiagonal

How to sort characters in a string diagonally


im splitting a string by the square number of his length..

String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int a = alphabet.length();
int b = (int)Math.round(Math.sqrt(a));

System.out.println(java.util.Arrays.toString(splitter(key, b))); 
// prints: [ABCDE, FGHIJ, KLMNO, PQRST, UVWXY, Z]

The splitter function:

public static String[] splitter(String s, int len) {
return s.split(String.format("(?<=\\G.{%1$d})", len));
}

What i want now is to sort it diagonal like this:

[0] = {A,B,D,G,K}
[1] = {C,E,H,L,P}
[2] = {F,I,M,Q,U}
[3] = {J,N,R,V,Y}
[4] = {O,S,W,Z,0}
[5] = {T,X,0,0,0}

I was trying to solve it with some loops by checking always if (i-1) >= i... but i get confused and kinda lost in here..


Solution

  • The solution I created below

    1. calculates the dimensions of the result matrix;
    2. uses those dimensions to initialize a two-dimensional result array with NUL character values;
    3. sets the values in the array based on the idea that for all elements on the same diagonal, the sum of their coordinates is constant.
    String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    double root = Math.sqrt(alphabet.length());
    int width = (int) Math.round(root);
    int height = width < root ? width + 1 : width;
    char[][] result = IntStream.range(0, height)
                               .mapToObj(i -> new char[width])
                               .toArray(i -> new char[height][]);
    
    int x = 0, y = 0, sum = 0;
    
    for (char c : alphabet.toCharArray()) {
        result[x][y] = c;
    
        y = x == Math.min(sum, height - 1) ? Math.min(++sum, width - 1) : y - 1;
        x = sum - y;
    }
    
    System.out.println(Arrays.deepToString(result));
    

    This yields the following output:

    [[A, B, D, G, K], [C, E, H, L, P], [F, I, M, Q, U], [J, N, R, V, Y], [O, S, W, Z,  ], [T, X,  ,  ,  ]]