Printing string in rows and column pattern Java

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

    When can't go straight turn left to walk, this is the theory used in this solution

    int dr[] = {0, 1, 0, -1};
    int dc[] = {1, 0, -1, 0};
    

    this is used for always move pattern. And curr & curc represent current position and curm represent current move pattern.

      public int[][] solve(int r, int c, String s) {
        int m[][] = new int[5][5];
        int curr = 0, curc = 0;
        
        for (int pos = 0, curm = 0; pos < r*c; pos++) {
          m[curr][curc] = (int) s.charAt(pos);
          if (curr + dr[curm] < 0 || curr + dr[curm] >= r || curc + dc[curm] < 0 || curc + dc[curm] >= c
              || m[curr + dr[curm]][curc + dc[curm]] != 0)
            curm = (curm + 1) % 4;
          curr = curr + dr[curm];
          curc = curc + dc[curm];
        }
        return m;
      }
    

    Then you can print this way

    for (int i = 0; i < r; i++) {
      for (int j = 0; j < c; j++) {
        System.out.printf("%c ", m[i][j]);
      }
      System.out.println("");
    }
    

提交回复
热议问题