Printing string in rows and column pattern Java

前端 未结 7 2269
孤独总比滥情好
孤独总比滥情好 2021-02-07 14:31

i\'m just created a java project to print string that is given in rows and column just like matrix. Here\'s the output that i just made:

h e l l o 
_ w o r l 
d _         


        
相关标签:
7条回答
  • 2021-02-07 15:33

    spiralMatrix(int s) returns s x s spiral matrix.

    static int[][] spiralMatrix(int s) {
        int[][] a = new int[s][s];
        int n = 0;
        for (int b = s - 1, c = 0, x = 0, y = 0, dx = 0, dy = 1; b > 0; b -= 2, x = y = ++c)
            for (int j = 0, t = 0; j < 4; ++j, t = dx, dx = dy, dy = -t)
                for (int i = 0; i < b; ++i, x += dx, y += dy, ++n)
                    a[x][y] = n;
        if (s % 2 == 1)
            a[s / 2][s / 2] = n;
        return a;
    }
    

    test

    for (int s = 0; s < 6; ++s) {
        int[][] a = spiralMatrix(s);
        System.out.println("s=" + s);
        for (int[] row : a)
            System.out.println(Arrays.toString(row));
        System.out.println();
    }
    

    result

    s=0
    
    s=1
    [0]
    
    s=2
    [0, 1]
    [3, 2]
    
    s=3
    [0, 1, 2]
    [7, 8, 3]
    [6, 5, 4]
    
    s=4
    [0, 1, 2, 3]
    [11, 12, 13, 4]
    [10, 15, 14, 5]
    [9, 8, 7, 6]
    
    s=5
    [0, 1, 2, 3, 4]
    [15, 16, 17, 18, 5]
    [14, 23, 24, 19, 6]
    [13, 22, 21, 20, 7]
    [12, 11, 10, 9, 8]
    

    And you can do it with this method.

    String str = "hello world its beautiful";
    int[][] spiral = spiralMatrix(5);
    int length = str.length();
    for (int x = 0, h = spiral.length, w = spiral[0].length; x < h; ++x) {
        for (int y = 0; y < w; ++y) {
            int p = spiral[x][y];
            System.out.print((p < length ? str.charAt(p) : " ") + " " );
        }
        System.out.println();
    }
    

    result

    h e l l o 
      b e a   
    s u l u w 
    t f i t o 
    i   d l r 
    
    0 讨论(0)
提交回复
热议问题