Printing string in rows and column pattern Java

前端 未结 7 2259
孤独总比滥情好
孤独总比滥情好 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:15

    Probably I'll add my answer too, idea is to flatten a two dimensional array to 1d and use the 1D array and transform it to a 2D spiral array. Hope it helps.

    Code:

    class Test {
    
        static String[][] spiralPrint(int m, int n, String[] a) {
            String[][] output = new String[m][n];
            int count = 0;
            int i, k = 0, l = 0;
            while (k < m && l < n) {
                for (i = l; i < n; ++i) {
                    output[k][i] = a[count++];
                }
                k++;
    
                for (i = k; i < m; ++i) {
                    output[i][n - 1] = a[count++];
                }
                n--;
    
                if (k < m) {
                    for (i = n - 1; i >= l; --i) {
                        output[m - 1][i] = a[count++];
                    }
                    m--;
                }
    
                if (l < n) {
                    for (i = m - 1; i >= k; --i) {
                        output[i][l] = a[count++];
                    }
                    l++;
                }
            }
            return output;
        }
    
        private static String[] flattenArray(String[][] input, int m, int n) {
            String[] output = new String[m * n];
            int k = 0;
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    output[k++] = input[i][j];
                }
            }
            return output;
        }
    
        public static void main(String[] args) {
    
            String[][] input = {
                    {"h", "e", "l", "l", "o"},
                    {"_", "w", "o", "r", "l"},
                    {"d", "_", "i", "t", "s"},
                    {"_", "b", "e", "a", "u"},
                    {"t", "i", "f", "u", "l"}};
    
            int m = 5;
            int n = 5;
    
            String[] flattenArray = flattenArray(input, m, n);
            String[][] spiralArray = spiralPrint(m, n, flattenArray);
    
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    System.out.print(spiralArray[i][j] + " ");
                }
                System.out.println();
            }
    
        }
    }
    
    Output:
    h e l l o 
    _ b e a _ 
    s u l u w 
    t f i t o 
    i _ d l r 
    

    Note: Indeed that I followed this Spiral transform to 1D, but it is not straight forward, I have re-modified to fit to the problem.

提交回复
热议问题