Skip to content

Instantly share code, notes, and snippets.

@jeffnash
Created February 7, 2016 23:07
Show Gist options
  • Select an option

  • Save jeffnash/5eb883c980c4253d6ef2 to your computer and use it in GitHub Desktop.

Select an option

Save jeffnash/5eb883c980c4253d6ef2 to your computer and use it in GitHub Desktop.
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.
public class Solution {
public ArrayList<ArrayList<Integer>> prettyPrint(int a) {
ArrayList<ArrayList<Integer>> sol = new ArrayList<ArrayList<Integer>>();
Integer size = 2 * a - 1;
for (int i = 0; i < size; i += 1) {
sol.add(new ArrayList<Integer>());
for (int j = 0; j < size; j += 1) {
sol.get(i).add(a);
}
}
//top half and middle
for (int i = 1; i < (size - 1) / 2 + 1; i += 1) {
int stepDowns = i;
int deficit = 0;
Boolean goUp = false;
//left side and middle
for (int j = 1; j <= (size - 1) /2; j += 1) {
if (stepDowns > 0) {
deficit += 1;
stepDowns -= 1;
sol.get(i).set(j, a - deficit);
} else {
sol.get(i).set(j, a - deficit);
}
}
stepDowns = i;
deficit = 0;
//right side
for (int j = size - 2; j > (size - 1) /2; j -= 1) {
if (stepDowns > 0) {
deficit += 1;
stepDowns -= 1;
sol.get(i).set(j, a - deficit);
} else {
sol.get(i).set(j, a - deficit);
}
}
}
int i = 0;
//well I'll be darned...the bottom two rows are the first two!
for (int j = size - 1; j > (size - 1) /2; j -= 1) {
sol.set(j, sol.get(i));
i += 1;
}
return sol;
//all 3's
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment