Published in

Buzz Code

# Java 8 | Pattern Practice 3 — Diamond

Hey guys! It’s already the third session to practice patterns! Since I started to post these pattern practices, I could see an huge increase in daily reading time of my posts. So I guess you guys are actually trying to solve the questions! I am so happy for that. Anyway what we’re gonna do today, is the Diamond pattern.

# Question 1. Make diamond.

`0000*000***00*****0*******00*****000***0000*`

We need to make the pattern above. Okay, we can just put the downward pyramid under the regular pyramid. And we know how to make pyramid from the last session. If you don’t checkout my last post.

Like this! So all we have to figure out is the downward pyramid. Let’s find the pattern of the last numbers of each line like the last time.
On the downward pyramid, row 1 ends with 7, row 2 ends with 6, row 3 ends with 5. It is pretty obvious that sum of the numbers of the row and its last number are all 8.
And the star parts starts from (row+2). So the answer would be below.

I think I can hear you guys are screaming that “This code is so ugly!”. I get it. Let’s improve this one a bit.

# Question 2. Make diamond only with 2 For statements and least number of If statement.

That is challenging…Let’s try to solve it by yourself first and scroll down as usual!

And that’s the hint, you see there are same patterns upside down after the row 0. Yes that’s right. We can use the absolute value here! Okay that’s all I can give you as a hint. You can do this! The answer is on below.

First we should see the last numbers of each line again. It’s (8-row) until the number of the row gets lower than 0. And it will be the same for the negative numbers of the row if we turn them into positive numbers! But how can we do so?

I declared the new variable `abNum` for that, and I assigned the value of `i` in it. And multiplied the abNum by -1 if it’s lower than 0.
Then I put the variable `j` from 1 to (8-abNum), So now the row 1 and -1, 2 and -2, 3 and -3 will have the same result!

Then I put zeros by using the if statement. Now there is a beautiful diamond with the shorter code!

That’s all for the pattern practice with me guys. With all the pattern practices we’ve done so far, I’m sure that now you can make the sand glass pattern or hollow diamond….etc. So on the next session I’ll talk about how to make the random number generator. So you can get the lucky numbers for the lottery tickets! See you guys!

--

--

Happy coding!