Maryam N. answered 07/27/15
Tutor
4
(6)
FIT Grad for Java & GRE (Quantitative)
First of all you should think how you can derive your magic number (INPUT argument) n which 4 in your example out of the OUTPUT.
Output in console shows 4 inclined lines of x's.
In short, I suggest the RECURSIVE ALGORITHM to solve this problem.
Define a global variable 'time' and declare it as an integer and initialize it with 0; This variable controls the spaces between each pair of X.
Write down your 'main' and call your method as below:
public static void main(String[] args) {
recurringPatterns(4); // the input argument varies from 0 to a desired integer.
}
recurringPatterns(4); // the input argument varies from 0 to a desired integer.
}
----------
method'd bulk:
There are three important parts in your method:
- The recursion termination for the recursive algorithm
- drawing the upper-side of the output (diamond)
- drawing the ower-side of the output
How to output upper-side line by line:
X
X X
X X X
X X X X
X X
X X X
X X X X
Termination Condition in this algorithm is:
if (n == 0) {
return;
}else{
....
}
// Now fill in the blank with the following piece of code:
// draw upper part of the output (diamond)
for (int i = 0; i < n - 1; i++) {
System.out.print(' '); // left-end space
}
for (int i = 0; i < time; i++) {
System.out.print('x');
System.out.print(' '); // middle space
}
System.out.println('x'); // right-end x
n--;
time++;
for (int i = 0; i < n - 1; i++) {
System.out.print(' '); // left-end space
}
for (int i = 0; i < time; i++) {
System.out.print('x');
System.out.print(' '); // middle space
}
System.out.println('x'); // right-end x
n--;
time++;
// At the time with the updated values of n and time your should be ready to RECALL the method:
recurringPatterns(n);
// Note that 'n' is subtracted by 1. and the value of variable 'time' is increased by 1.
// We are here because the algorithm satisfied the Recursion Termination. Thus, the value of n should be 0 by time.
// Reverse the whole operation above
// draw lower part of the output
n++;
time--;
if (time != 0) {
for (int i = 0; i < n; i++) {
System.out.print(' ');
}
for (int i = 0; i < time - 1; i++) {
System.out.print('x');
System.out.print(' '); // middle space
}
System.out.println('x'); // right-end x
} else {
return;
}
// draw lower part of the output
n++;
time--;
if (time != 0) {
for (int i = 0; i < n; i++) {
System.out.print(' ');
}
for (int i = 0; i < time - 1; i++) {
System.out.print('x');
System.out.print(' '); // middle space
}
System.out.println('x'); // right-end x
} else {
return;
}
X X X
X X
X
X X
X
Please note that this algorithm handles having no space after right-end X in each line.
Let me know if you need further description for more details.