Skip to content

Instantly share code, notes, and snippets.

@lamchau
Last active June 8, 2018 09:55
Show Gist options
  • Save lamchau/fe0614c29e31f4ebc65ca790e305e5dc to your computer and use it in GitHub Desktop.
Save lamchau/fe0614c29e31f4ebc65ca790e305e5dc to your computer and use it in GitHub Desktop.
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.

@lamchau
Copy link
Author

lamchau commented May 31, 2018

  private static String toString(List<?> list) {
    if (list == null) {
      return "";
    }
    Collector<CharSequence, ?, String> collector = Collectors.joining(" ");
    return list.stream()
        .map(String::valueOf)
        .collect(collector);
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment