lamchau
5/31/2018 - 7:34 AM

https://www.interviewbit.com/problems/prettyprint/

class Solution {
  public static List<List<Integer>> prettyPrint(int A) {
    List<List<Integer>> list = new ArrayList<>();

    // rows/columns (nxn)
    final int columns = A + (A - 1);
    final int midpoint = columns / 2;

    // track current layer
    int layer = 1;

    // create top half
    for (int i = 0; i <= midpoint; i++) {
      List<Integer> row = Arrays.asList(new Integer[columns]);
      if (i == 0) {
        Collections.fill(row, A);
      } else {
        // use previous row as a reference
        Collections.copy(row, list.get(i - 1));

        // shrink each layer
        for (int j = layer; j < columns - layer; j++) {
          row.set(j, row.get(j) - 1);
        }
        layer++;
      }
      list.add(row);
    }

    // mirror bottom half
    for (int i = 1; i <= midpoint; i++) {
      list.add(list.get(midpoint - i));
    }
    return list;
  }
}

Print concentric rectangular pattern in a 2d matrix. Let us show you some examples to clarify what we mean.

Example 1:

Input: A = 4. Output:

4 4 4 4 4 4 4 
4 3 3 3 3 3 4 
4 3 2 2 2 3 4 
4 3 2 1 2 3 4 
4 3 2 2 2 3 4 
4 3 3 3 3 3 4 
4 4 4 4 4 4 4 

Example 2:

Input: A = 3. Output:

3 3 3 3 3 
3 2 2 2 3 
3 2 1 2 3 
3 2 2 2 3 
3 3 3 3 3 

The outermost rectangle is formed by A, then the next outermost is formed by A-1 and so on.

You will be given A as an argument to the function you need to implement, and you need to return a 2D array.