Draw a Christmas tree using java - java

b) drawChristmasTree(int n) which takes as an input one integer value n
and then output on console a Christmas tree in which last part height equals n. The tree consists of pyramids of heights from 1 to n. The shape have to be as presented below (for
n=4):
X
X
XXX
X
XXX
XXXXX
X
XXX
XXXXX
XXXXXXX
I tried to do it but the output was:
X
X
XXX
X
XXX
XXXXX
X
XXX
XXXXX
XXXXXXX
My coding:
public static void drawChristmassTree(int n) {
n=1;
while(n<=4){
int rowCount =1;
for(int i = n ; i>0 ; i--) {
for(int j=1; j<=i; j++) {
System.out.print(" ");
}
for(int j=1; j<=rowCount; j++ ) {
System.out.print("X");
}
for(int j=2; j<=rowCount; j++ ) {
System.out.print("X");
}
System.out.println();
rowCount++;
}
n++;
}
}
Does anyone have any idea how to move it to the right?

My approach
In order to solve this problem, I started out writing out each case (e.g. n=1, n=2, n=3...) and ended up with something like this:
if (n < 1) {
return;
}
if (n == 1) {
System.out.println(" X ");
}
else if (n == 2) {
System.out.println(" X "); // n-1 spaces
System.out.println(" X ");
System.out.println("XXX"); // 1, 3, 5, 7, ... n+2 pattern
}
else if (n == 3) {
System.out.println(" X "); // n-1 spaces
System.out.println(" X ");
System.out.println(" XXX "); // 3
System.out.println(" X ");
System.out.println(" XXX ");
System.out.println("XXXXX"); // 5
}
Once I had a handle of the pattern, I was able to build the first function to handle drawing a single tier on the tree:
public static void drawTier(int currentTier, int numberOfTiers) {
if (currentTier < 1) {
return;
}
for (int i = 0; i < currentTier; i++) {
for (int j = i; j < numberOfTiers - 1; j++) {
System.out.print(" ");
}
int width = i + (i % currentTier);
for (int k = 0; k <= width; k++) {
System.out.print("X");
}
System.out.println();
}
}
Now we can build a wrapper to build n number of tiers:
public static void drawTree(int numberOfTiers) {
if (numberOfTiers < 1) {
return;
}
for (int i = 1; i <= numberOfTiers; i++) {
drawTier(i, numberOfTiers);
}
}
and finally, we can give it a try:
public static void main(String[] args) {
drawTree(4);
}
Final output:
X
X
XXX
X
XXX
XXXXX
X
XXX
XXXXX
XXXXXXX

Related

(Java Number Pyramid) How do I get my numbers to have more spaces between them while lining up accurately when it is an integer is > 9?

I am having difficulty getting the desired output. I know there are problems that are similar to mine that is already posted, but I find it hard to relate my code to their solutions without a massive overhaul.
The solution for my class assignment:
Supposed to continue until every direction of pyramid equals 1
My second method "spaces" is redundant and I am not sure why. Any help would be appreciated.
Blockq
public static void main(String[] args) {
numPar();
spaces();
}
private static void spaces() {
int x = 0;
if(x > 0 && x < 10) {
System.out.print(" ");
} else if (x > 10 && x < 99) {
System.out.print(" ");
} else if (x > 99) {
System.out.print(" ");
}
}
private static void numPar() {
int spaces = 14;
for(int i = 0; i<= 7; i++) {
for(int u = 0; u<spaces; u++) {
System.out.print(" ");
}
spaces--;
spaces--;
for(int j = 0 ; j <i ; j++) {
System.out.print(""+ (int) Math.pow(2,j)+" ");
}
for(int k = i ; k >=0 ; k--) {
System.out.print(""+ (int) Math.pow(2,k)+" ");
}
System.out.println("");
}
}
}
I made every number take 3 places using String.format("%3s", (int) Math.pow(2, j)). You can make it dynamic by replacing the number 3 here with the length of the largest number you'll print. I also changed the number of spaces in your print statements. Here is the full code that prints an evenly spaced pyramid:-
public static void main(String[] args) {
numPar();
spaces();
}
private static void spaces() {
int x = 0;
if (x > 0 && x < 10) {
System.out.print(" ");
} else if (x > 10 && x < 99) {
System.out.print(" ");
} else if (x > 99) {
System.out.print(" ");
}
}
private static void numPar() {
int spaces = 14;
for (int i = 0; i <= 7; i++) {
for (int u = 0; u < spaces; u++) {
System.out.print(" ");
}
spaces--;
spaces--;
for (int j = 0; j < i; j++) {
System.out.print("" + String.format("%3s", (int) Math.pow(2, j)) + " ");
}
for (int k = i; k >= 0; k--) {
System.out.print("" + String.format("%3s", (int) Math.pow(2, k)) + " ");
}
System.out.println("");
}
}
String.format explanation:-
String.format("%3s", str) will print the string str, padding it with spaces, to make the total length 3 if it's less than 3. Note that you can write anything instead of 3 - I used 3 because your biggest number was of length 3.
So "A" will be printed as "_ _ A" (2 spaces), and "Ab" will be printed as "_ Ab" (1 space).
I just replaced str with your Math.pow(2, j).

Empty diamond shape with numbers

So I have been asked this question and I could only solve the top part of the code, I am stuck on the bottom part.
Write a Java program called EmptyDiamond.java that contains a method that takes an integer n and prints a empty rhombus on 2n − 1 lines as shown below. Sample output where n = 3:
1
2 2
3 3
2 2
1
Here's my code so far:
public static void shape(int n) {
//TOP PART
for (int i = 1; i <= (n - 1); i++) {
System.out.print(" ");
}
System.out.println(1);
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= (n - i); j++) {
System.out.print(" ");
}
System.out.print(i);
for (int j = 1; j <= 2 * i - n + 1; j++) {
System.out.print(" ");
}
System.out.println(i);
}
//BOTTOM PART (The messed up part)
for (int i = n + 1; i <= 2 * n - 2; i++) {
for (int j = 1; j <= n - i; j++) {
System.out.print(" ");
}
System.out.print(i);
for (int j = 1; j <= n; j++) {
System.out.print(" ");
}
System.out.print(i);
}
for (int i = 1; i <= (n - 1); i++) {
System.out.print(" ");
}
System.out.println(1);
}
public static void main(String[] args) {
shape(4);
}
Maybe a little bit late, but because the bottom part of your message is just the first part mirrored you can use a Stack to print the message in reverse order:
public static void main(String[] args) {
int maxNumber = 3;
Stack<String> message = new Stack<>();
// upper part
for (int row = 0; row < maxNumber; row++) {
int prefix = maxNumber - (row + 1);
int spaces = row >= 2 ? row * 2 - 1 : row;
String line = getLine(row, prefix, spaces);
System.out.println(line);
if (row != maxNumber - 1)
message.add(line);
}
// bottom part
while (!message.isEmpty())
System.out.println(message.pop());
}
public static String getLine(int row, int prefix, int spaces) {
StringBuilder line = new StringBuilder("_".repeat(prefix));
line.append(row + 1);
if (row != 0) {
line.append("_".repeat(spaces));
line.append(row + 1);
}
return line.toString();
}
Output:
__1
_2_2
3___3
_2_2
__1
You can of course use any method you want to fill the stack (i.e. to generate the upper part of your message) like with the method this question suggessted. This upper part I describe contains the first line (inclusive) up to the middle line (exclusive).
Here is the program for printing empty diamond:
int n = 3; //change the value of n to increase the size of diamond
int upperCount = 1;
for (int i = n; i >= 1; i--) {
for (int j = i; j >= 1; j--) {
System.out.print(" ");
}
System.out.print(upperCount);
for (int j = 0; j <= upperCount - 2; j++) {
System.out.print(" ");
}
for (int j = 0; j <= upperCount - 2; j++) {
System.out.print(" ");
}
if (upperCount != 1) {
System.out.print(upperCount);
}
upperCount++;
System.out.print("\n");
}
int lowerCount = n - 1;
for (int i = 1; i <= n - 1; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(" ");
}
System.out.print(lowerCount);
for (int j = 0; j <= lowerCount - 2; j++) {
System.out.print(" ");
}
for (int j = 0; j <= lowerCount - 2; j++) {
System.out.print(" ");
}
if (lowerCount != 1) {
System.out.print(lowerCount);
}
lowerCount--;
System.out.print("\n");
}
Do following changes in the Bottom Part of your code:
int lowerCount = n - 1;
for (int i = n - 1; i >= 2; i--) {
for (int j = 1; j <= (n - i); j++) {
System.out.print(" ");
}
System.out.print(i);
for (int j = 1; j <= lowerCount; j++) {
System.out.print(" ");
}
System.out.print(i);
lowerCount -= 2;
}
You can print an empty diamond shape with numbers using two nested for loops over rows and columns from -n to n. The diamond shape is obtained when iAbs + jAbs == n:
int n = 2;
for (int i = -n; i <= n; i++) {
// absolute value of 'i'
int iAbs = Math.abs(i);
for (int j = -n; j <= n; j++) {
// absolute value of 'j'
int jAbs = Math.abs(j);
// empty diamond shape
System.out.print(iAbs + jAbs == n ? jAbs + 1 : " ");
if (j < n) {
System.out.print(" ");
} else {
System.out.println();
}
}
}
Output:
1
2 2
3 3
2 2
1
You can separately define width and height:
int m = 4;
int n = 2;
int max = Math.max(m, n);
for (int i = -m; i <= m; i++) {
// absolute value of 'i'
int iAbs = Math.abs(i);
for (int j = -n; j <= n; j++) {
// absolute value of 'j'
int jAbs = Math.abs(j);
// empty diamond shape
System.out.print(iAbs + jAbs == max ? jAbs + 1 : " ");
if (j < n) {
System.out.print(" ");
} else {
System.out.println();
}
}
}
Output:
1
2 2
3 3
3 3
2 2
1
See also:
• Filling a 2d array with numbers in a rhombus form
• How to print a diamond of random numbers?
java-11
Using String#repeat introduced as part of Java-11, you can do it using a single loop.
public class Main {
public static void main(String[] args) {
int n = 3;
for (int i = 1 - n; i < n; i++) {
int x = Math.abs(i);
System.out.println(" ".repeat(x) + (n - x)
+ " ".repeat(Math.abs((n - x) * 2 - 3))
+ ((i == 1 - n || i == n - 1) ? "" : (n - x)));
}
}
}
Output:
1
2 2
3 3
2 2
1
You can print a variant of the diamond simply by increasing the amount of space by one character:
public class Main {
public static void main(String[] args) {
int n = 3;
for (int i = 1 - n; i < n; i++) {
int x = Math.abs(i);
System.out.println(" ".repeat(x) + (n - x)
+ " ".repeat(Math.abs((n - x) * 2 - 3))
+ ((i == 1 - n || i == n - 1) ? "" : (n - x)));
}
}
}
Output:
1
2 2
3 3
2 2
1
Alternative solution:
public static void main(String[] args) {
int n = 7;
for (int i = -n; i <= n; i++) {
for (int j = -n; j <= n; j++) {
// edge of the diamond
int edge = Math.abs(i) + Math.abs(j);
// diamond shape with numbers
if (edge == n) System.out.print(n - Math.abs(i) + 1);
// beyond the edge && in chessboard order || vertical borders
else if (edge > n && (i + j) % 2 != 0 || Math.abs(j) == n)
System.out.print("*");
// empty part
else System.out.print(" ");
}
System.out.println();
}
}
Output:
** * * 1 * * **
* * * 2 2 * * *
** * 3 3 * **
* * 4 4 * *
** 5 5 **
* 6 6 *
*7 7*
8 8
*7 7*
* 6 6 *
** 5 5 **
* * 4 4 * *
** * 3 3 * **
* * * 2 2 * * *
** * * 1 * * **
See also: How to print a given diamond pattern in Java?
Solution: Java program called EmptyDiamond.java that contains a method that takes an integer n and prints a empty rhombus on 2n − 1 lines.
public class EmptyDiamond {
public static void main(String[] args) {
shape(3); // Change n to increase size of diamond
}
public static void shape(int n) {
int max = 2 * n - 1; // length of the diamond - top to bottom
int loop = 0; // with of each loop. initialized with 0
for (int i = 1; i <= max; i++) {
int val = 0;
if (i <= n) {
loop = n + i - 1;// e.g. when i = 2 and n = 3 loop 4 times
val = i; // value to be printed in each loop ascending
} else {
loop = n + (max - i); //e.g. when i = 4 and n = 3 loop 4 times
val = max - i + 1; // value to be printed in each loop descending
}
for (int j = 1; j <= loop; j++) {
// (value end of loop)
// || (value in the beginning when i <= n)
// || (value in the beginning when i > n)
if (j == loop
|| j == (n - i + 1)
|| j == (n - val + 1)) {
System.out.print(val); // Print values
} else {
System.out.print(" "); // Print space
}
}
System.out.println(); // Print next line
}
}
}
Output when n = 3:
1
2 2
3 3
2 2
1
Stream-only function:
public static void printEmptyDiamond(int n) {
IntStream.range(1, 2*n)
.map(i-> i > n ? 2*n-i : i)
.mapToObj(i -> " ".repeat(n-i) + i + (i>1 ? " ".repeat(2*(i-1)-1)+i : ""))
.forEach(System.out::println);
}
Example output (printEmptyDiamond(7)):
1
2 2
3 3
4 4
5 5
6 6
7 7
6 6
5 5
4 4
3 3
2 2
1
With explainations:
public static void printEmptyDiamond(int n) {
IntStream.range(1, 2*n)
.map(i-> i > n? 2*n-i : i) // numbers from 1 to n ascending, then descending to 1 again
.mapToObj(i -> " ".repeat(n-i) // leading spaces
+ i // leading number
+ (i>1 ? // only when number is > 1
" ".repeat(2*(i-1)-1) // middle spaces
+ i // trailing number
: ""))
.forEach (System.out::println);
}
I did it for fun, here's the code :
import java.util.Scanner;
public class Diamond {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int num = read.nextInt();
read.nextLine();
//TOP
for(int i = 1;i<=num;i++) {
//LEFT
for(int k = i; k<num;k++) {
if ( k % 2 == 0 ) {
System.out.print(" ");
}
else {
System.out.print(" ");
}
}
if(i>1) {
for(int j =1;j<=i;j++) {
if (j==1 || j== i) {
for(int u=0;u<j;u++) {
System.out.print(" ");
}
System.out.print(i);
}
else {
System.out.print(" ");
}
}
System.out.println("");
}
else {
System.out.println(" "+i);
}
}
//BOTTOM
for(int i = num-1;i>0;i--) {
for(int k = i; k<num;k++) {
if ( k % 2 == 0 ) {
System.out.print(" ");
}
else {
System.out.print(" ");
}
}
if(i>1) {
for(int j =1;j<=i;j++) {
if (j==1 || j== i) {
for(int u=0;u<j;u++) {
System.out.print(" ");
}
System.out.print(i);
}
else {
System.out.print(" ");
}
}
System.out.println("");
}
else {
System.out.println(" "+i);
}
}
}
}
And the output :
7
1
2 2
3 3
4 4
5 5
6 6
7 7
6 6
5 5
4 4
3 3
2 2
1
Having seen the other answers, there's a whole load of loops I could've skipped. Just decided to wing it at the end and do it as quick as possible.

Can't print the pattern

I created the code that should print a pattern like
12345
2345
345
45
5
I have the code written below, the logic works fine in python but in java the output is different.
class Testing{
public static void main(String args[])
{
for (int i = 1; i<6;i++)
{
for (int j =0; j<i-1;j++)
{
System.out.print(" ");
}
while (i < 6){
System.out.print(k);
System.out.println();
i++;
}
}
}
}
The output is just 12345. I don't understand why does it iterate over first for loop for only once.
Use another variable for while control.
public class Testing {
public static void main(String args[]) {
int k;
for (int i = 1; i < 6; i++) {
for (int j = 0; j < i - 1; j++) {
System.out.print(" ");
}
k = i;
while (k < 6) {
System.out.print(k);
k++;
}
System.out.println();
}
}
}
You can see this in this link
this will show you :
12345
2345
345
45
5
Note: When 'while loop' increases. That increases i value bigger than 6. So next time it terminates the outer loop. That was your mistake.
package com.appointment.api;
class Testing {
public static void main(String args[]) {
for (int i = 1; i < 6; i++) {
System.out.println();
for (int j = 0; j < i - 1; j++) {
System.out.print(" ");
}
int x = i;
while (x < 5) {
System.out.print(i);
x++;
}
}
}
}
Following is a java-8 implementation of the problem:
IntStream.rangeClosed(1, MAX)
.forEach(i -> IntStream.rangeClosed(1, MAX)
.mapToObj(j -> j == MAX ? j + "\n" : j >= i ? j : " ")
.forEach(System.out::print)
);
Set MAX = 5 and it will print your pattern.
Output:
12345
2345
345
45
5

Print a Z shape pyramid using * stars

I am trying to write a program that outputs a Z pattern that is n number of * across the top, bottom, and connecting line using for loops.
Example:
Enter a number: 6
******
*
*
*
*
******
This is my current code, it's producing a half pyramid upside down.
import java.util.*;
public class ZShape {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = input.nextInt();
for (int x = 0; x <= n; x++) {
for (int y = n; y >= 1; y--) {
if (y > x) {
System.out.print("* ");
}
else
System.out.print(" ");
}
System.out.println();
}
}
}
This is the logic in the following code:
Loop over each row of the output (so from 0 to n excluded so that we have n rows)
Loop over each column of the output (so from 0 to n excluded so that we have n columns)
We need to print a * only when it is the first row (x == 0) or the last row (x == n - 1) or the column is in the opposite diagonal (column == n - 1 - row)
Code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = input.nextInt();
for (int row = 0; row < n; row++) {
for (int column = 0; column < n; column++) {
if (row == 0 || row == n - 1 || column == n - 1 - row) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
Sample output for n = 6:
******
*
*
*
*
******
(Note that this output has trailing white-spaces for each row, you did not specify whether they should be included, but it is easy to remove them by adding another check).
How about using three loops instead?
for (int x = 0; x < n; x++) {
System.out.print("*");
}
System.out.println();
for (int x = n-3; x >= 0; x--) {
for (int y = x; y >= 0; y--) {
System.out.print(" ");
}
System.out.println("*");
}
for (int x = 0; x < n; x++) {
System.out.print("*");
}
public class Star {
public static void main(String[] args) {
for (int i = 0; i <=4; i++) {
for (int j = 0; j <=4; j++)
{
if (i==4 || (i+j)==4 || i==0)
{
System.out.print(" * ");
}
else
{
System.out.print(" ");
}
}
System.out.println(" ");
}
}
}
Here is a logic to print Z shape:
when i = 1, then the First line will print only "#"
when i = n, then the Last line will print in same way by "#" only
when i = j, that means it will execute one diagonal line by "#" only
Code:
public static void main(String[] args) {
Scanner scr = new Scanner(System.in);
int n = scr.nextInt();
for (int i = 1; i <= n; i++) {
for(int j = n; j >= 1; j--) {
if (i == 1 || i == n || i == j) {
System.out.print("# ");
}
else {
System.out.print(" ");
}
}
System.out.println();
}
}

writiting the code with the appropriate variable values

I should Write a program Square.java that declares and initalizes a variable n (with n ≥ 2) and prints out a two dimensional n-by-n triangular pattern as shown below (where n=6).
public class Square {
public static void main (String[]args){
for (int Line=1; Line<= 6; Line ++){
for (int n=1; n<= (Line-1*1); n++) {
System.out.print ("# ");
}
for (int n=1; n<= (7-Line); n++){
System.out.print ("$ ");
}
System.out.println ("");
}
}
}
I can't manage to write the code with n>=6 or n=2
I am guessing you are forgetting to update the 7 when you change the 6. Put your size in a variable as shown below. Seems to work for me for 2 and any other size
public static void main(String[] args) {
int size = 6;
for (int Line = 1; Line <= size; Line++) {
for (int n = 1; n <= (Line - 1 * 1); n++) {
System.out.print("# ");
}
for (int n = 1; n <= ((size + 1) - Line); n++) {
System.out.print("$ ");
}
System.out.println("");
}
}
The size of the square must be an attribut of the class
The result :
public class Square {
public int size;
public Square(int size) {
this.size = size;
}
public void goSquare(){
for (int line=1; line<= size; line++){
for (int n=1; n<= (line-1); n++) {
System.out.print ("# ");
}
for (int n=1; n<= ((size+1)-line); n++){
System.out.print ("$ ");
}
System.out.println ("");
}
}
public static void main (String[]args){
Square square = new Square(6);
square.goSquare();
}
}
In your actual code 7-Line is what blocks values >=6 and for value =2 your code works great but it only prints one element(point).
Another thing if you use Line-1*1 you mean (Line-1)*1 which is equivalent to write Line-1.
Also in 7-Line the value 7 should be an attribute to be used in the first loop too in Line <= 7, you can see it in this working code:
int max = 2;
for (int Line = 1; Line <= max; Line++) {
for (int n = 1; n <= (Line - 1); n++) {
System.out.print("# ");
}
for (int n = 1; n <= (max - Line); n++) {
System.out.print("$ ");
}
System.out.println("");
}
And this is an Ideone Working Example of the code.

Categories

Resources