Empty diamond shape with numbers - java

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.

Related

half pyramid inverted with even number

half the pyramid is inverted with an even number, and each line omits the starting and ending numbers, so that the output expectation are as shown below.
Expected output
2 4 6 8 10
4 6 8
6
but I have tried my code below with the results that do not match my expectations.
My code
public static void main(String[] args) {
int rows = 5;
for (int i = rows; i >=1 ; i--) {
for (int j = 1; j <=2*i ; j++) {
if (j % 2 == 0){
System.out.print(j + " ");
}
}
System.out.println();
}
}
My output
2 4 6 8 10
2 4 6 8
2 4 6
2 4
2
Question:
how to solve the problem is?
You need to change the starting value of j as well and limit how often your first loop runs depending on rows:
int rows = 5;
for (int i = rows; i >= rows / 2; i--) {
for (int j = 2 + 2 * (rows - i); j <= 2 * i; j += 2) {
System.out.print(j + " ");
}
System.out.println();
}
Currently, you are starting the inner loop as int j = 1. Instead of a fixed start, it should be variable.
Replace
int j = 1;
with
int j = 2 * (rows - i + 1) - 1;
The starting condition of j should depend on i, also you can remove the if using j += 2 as increment statement
int rows = 5;
for (int i = rows; i >= 1; i--) {
for (int j = 2 * (rows - i + 1); j <= 2 * i; j += 2) {
System.out.print(j + " ");
}
System.out.println();
}
'rows' is a bad name. Can you see why?
here's the code:
public static void main(String[] args) {
int columns = 5;
for (int currentColumn = 0; currentColumn < columns ; currentColumn++) {
for (int j = currentColumn; j < columns-currentColumn ; j++) {
System.out.print((2*j+2) + " ");
}
System.out.println();
}
}
First, try to understand the pattern. For each iteration, the number of elements in a column is decreasing by 2. So consider the below code
public static void main(String[] args) {
int input = 5, multiplier = 2;
for(int numberOfRows = input; numberOfRows >= 1; numberOfRows -= 2) {
for(int columns = 1; columns <= numberOfRows; columns += 1) {
System.out.print(columns * multiplier + "\t");
}
System.out.println();
}
}

(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).

Display a box of increasing number with order

CODE
int rows=3, columns=3, i, j;
for(i = 1; i <= rows; i++)
{
for(j = 1; j <= columns; j++)
{
if(i == 1 || i == rows || j == 1 || j == columns)
{
System.out.print(count);
count++;
}
else
{
System.out.print(" ");
}
}
System.out.print("\n");
}
The following piece of code outputs the following:
OUTPUT
123
4 5
678
What I'm trying to achieve is the following:
123
8 4
765
Basically creating a board game which has to start from one position and end at the same position completing a full circle., in this case a square.
Any Ideas ??
After some experiments, this could work:
public static void printBox(int rows, int columns) {
int sumOfColumns = 2 * columns + rows - 1;
int sumOfRow = 2 * columns + 2 * rows - 2;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= columns; j++) {
if (i == 1) {
System.out.printf(String.format("%3d", j));
} else if (j == 1) {
System.out.printf(String.format("%3d", sumOfRow - (i + j - 1)));
} else if (j == columns) {
System.out.printf(String.format("%3d", i + j - 1));
} else if (i == rows) {
System.out.printf(String.format("%3d", sumOfColumns - j));
} else {
System.out.print(" ");
}
}
System.out.print("\n");
}
System.out.print("\n");
}
Test case:
public static void main(String[] args) {
printBox(3, 3);
printBox(4, 4);
printBox(3, 4);
}
Result:
1 2 3
8 4
7 6 5
1 2 3 4
12 5
11 6
10 9 8 7
1 2 3 4
10 5
9 8 7 6
Consider creating a 2 dimensional array:
gameBoard[3][3];
then populate that board with the desired values. After the gameboard is complete, you can write another function to print the board.

Making a pattern with java using nested loops

I have to make a pattern that is of a diamond shape such as this:
1
1 2
1 2 3
1 2 3 4 5
1 2 3
1 2
1
I wrote this ( sorry if for the variable name, this is just a small part of my program and I'm trying to get the pattern right so I didn't mind my variables at the moment):
public class NewFile{
public static void main(String []args){
int k = 0;
for (int i=1 ; i<=5 ; i++)
{
{ for (int h=2 ; h >= i ; h--)
System.out.print(" ");
for (int j=1 ; j<= i + k ; j++)
System.out.print(j);
for (int w=2 ; w>= i; w--)
System.out.print(" ");
}
k++;
System.out.println();}
}
}
My output is the following:
1
123
12345
1234567
123456789
I realize I should divide the code into a lower and upper triangle using two loops. However, I don't know how to break the first part. I did find the "trend" but I don't see how to implement it.
The following code will display a diamond shape that is made up of asterisks:
int i = 0, j, k, n;
n = 7; // 7 characters high. Change as needed.
for (k = 1; k <= (n + 1) / 2; k++) {
for (i = 0; i < n - k; i++) {
System.out.print(" ");
}
for (j = 0; j < k; j++) {
System.out.print("* ");
}
System.out.println("");
}
for (k = ((n + 1) / 2); k < n; k++) {
for (i = 1; i < k; i++) {
System.out.print(" ");
}
for (j = 0; j < n - k; j++) {
System.out.print(" *");
}
System.out.println("");
}
The integer n represents the height of the diamond in characters and can be changed as needed.

Pascal's Triangle Format [duplicate]

This question already has answers here:
Pascal's triangle 2d array - formatting printed output
(5 answers)
Closed 1 year ago.
The assignment is to create Pascal's Triangle without using arrays. I have the method that produces the values for the triangle below. The method accepts an integer for the maximum number of rows the user wants printed.
public static void triangle(int maxRows) {
int r, num;
for (int i = 0; i <= maxRows; i++) {
num = 1;
r = i + 1;
for (int col = 0; col <= i; col++) {
if (col > 0) {
num = num * (r - col) / col;
}
System.out.print(num + " ");
}
System.out.println();
}
}
I need to format the values of the triangle such that it looks like a triangle:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
I can't for the life of me figure out how to do that. Please answer keeping in mind that I'm a beginner in Java programming.
public static long pascalTriangle(int r, int k) {
if (r == 1 || k <= 1 || k >= r) return 1L;
return pascalTriangle(r - 1, k - 1) + pascalTriangle(r - 1, k);
}
This method allows you to find the k-th value of r-th row.
This is a good start, where it's homework, I'll leave the rest to you:
int maxRows = 6;
int r, num;
for (int i = 0; i <= maxRows; i++) {
num = 1;
r = i + 1;
//pre-spacing
for (int j = maxRows - i; j > 0; j--) {
System.out.print(" ");
}
for (int col = 0; col <= i; col++) {
if (col > 0) {
num = num * (r - col) / col;
}
System.out.print(num + " ");
}
System.out.println();
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
In each row you will need to print:
n spaces
m numbers
n spaces
Your job is to figure out n (which will be zero in the last line) and m based on row number.
[This is more like a comment but I needed more formatting options than comments provide]
You need to print the spaces (like others have mentioned) and also as this is homework I'm leaving it to you but you might want to look at this handy little function
System.out.printf();
Here is a handy reference guide
Also note that you will need to take into account that some numbers are more than 1 digit long!
import java.util.*;
class Mine {
public static void main(String ar[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 1; i < n; i++) {
int size = 1;
for (int j = 1; j <= i; j++) {
int a[] = new int[size];
int d[] = new int[size];
for (int k = 1; k <= size; k++) {
a[1] = 1;
a[size] = 1;
for (int p = 1; p <= size; p++) {
d[p] = a[p];
}
if (size >= 3) {
for (int m = 2; m < size; m++) {
a[m] = d[m] + d[m - 1];
}
}
}
for (int y = 0; y < size; y++) {
System.out.print(a[y]);
}
System.out.println(" ");
}
++size;
}
}
}
public class HelloWorld {
public static void main(String[] args) {
int s = 7;
int k = 1;
int r;
for (int i = 1; i <= s; i++) {
int num = 1;
r = i;
int col = 0;
for (int j = 1; j <= 2 * s - 1; j++) {
if (j <= s - i)
System.out.print(" ");
else if (j >= s + i)
System.out.print(" ");
else {
if (k % 2 == 0) {
System.out.print(" ");
} else {
if (col > 0) {
num = num * (r - col) / col;
}
System.out.print(num + " ");
col++;
}
k++;
}
}
System.out.println("");
k = 1;
}
}
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
You can try this code in java. It's simple :)
public class PascalTriangle {
public static void main(String[] args) {
int rows = 10;
for (int i = 0; i < rows; i++) {
int number = 1;
System.out.format("%" + (rows - i) * 2 + "s", "");
for (int j = 0; j <= i; j++) {
System.out.format("%4d", number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
Code perfectly prints pascal triangle:
public static void main(String[] args) {
int a, num;
for (int i = 0; i <= 4; i++) {
num = 1;
a = i + 1;
for (int j = 4; j > 0; j--) {
if (j > i)
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
if (j > 0)
num = num * (a - j) / j;
System.out.print(num + " ");
}
System.out.println();
}
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Categories

Resources