I\'m a novice in java and I\'m a little bit of trouble trying to get the output I need. I\'m trying to make a Diamond outline pattern using nested loops in java. The output I ne
Alright, this is how you have to look at it.
LEFT SIDE:
Example n=4 (same as above). We need to print 5 lines that contain 2 chars if n=4. We need to figure out how many spaces each line needs for this left side. x is line # and y is # of spaces.
x y
1 3
2 2
3 1
4 2
5 3
Now we need a linear function, y=mx+b, that will create the above table.
The answer is y=|x-3|+1.
Now, rather than the example of n=4, what will this linear function be for any n?
y=|x-(n-1)|+1.
or, in java,
int y = Math.abs(x - (n-1)) + 1;
RIGHT SIDE
Now, repeat with right side of the diamond. X is line # and y is # of spaces required.
x y
1 2
2 4
3 6
4 4
5 2
Again, we need a linear function that creates this table.
The answer is y=6-|3-x|*2.
Again, for any n, you will get
int y= (2*(n-1)) - Math.abs((n-1) - x)*2;
Filling in #s rather than x's and printing the top and bottom points should be easy, didn't include it below.
After doing all this, I realized the top and bottom points cannot be a perfect point (can't do half spaces), so the functions will need modification to the following...
int secondSpace = (2*(n-1)) - Math.abs((n-1) - i)*2;
will become
int secondSpace = (2*(n-1)) - Math.abs((n-1) - i)*2-1;
public static void drawDiamond(int n) {
int numbLinesWith2xs = 2*n - 3;
for (int i = 1; i <= numbLinesWith2xs; i++) {
int firstSpace = Math.abs(i - (n-1)) + 1;
int secondSpace = (2*(n-1)) - Math.abs((n-1) - i)*2;
printSpaces(firstSpace);
System.out.print("x");
printSpaces(secondSpace);
System.out.println("x");
}
}
public static void printSpaces(int n) {
for (int i=1; i<=n; i++) {
System.out.print(" ");
}
}
//RESULT for drawDiamond(8):
x x
x x
x x
x x
x x
x x
x x
x x
x x
x x
x x
x x
x x
final solution with everything included:
public static void drawDiamond(int n) {
int numbLinesWith2xs = 2*n - 3;
printSpaces(n);
System.out.println("1");
for (int i = 1; i <= numbLinesWith2xs; i++) {
int firstSpace = Math.abs(i - (n-1)) + 1;
int secondSpace = (2*(n-1)) - Math.abs((n-1) - i)*2-1;
printSpaces(firstSpace);
System.out.print(secondSpace/2+2);
printSpaces(secondSpace);
System.out.println(secondSpace/2+2);
}
printSpaces(n);
System.out.println("1");
}
1
2 2
3 3
4 4
3 3
2 2
1