I am writing some code that creates a incrementing number right angle triangle that looks something like this:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
I am unsure on how to make my code output a triangle to that shape as my code outputs the same thing except inverted.
This is the code I have:
public class Main {
public static void main(String[] args) {
int rows = 6;
for (int i = 1; i <= rows; ++i) {
for (int j = 1; j <= i; ++j) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
My speculation is that instead of incrementing some of the values I would decrement them however the code would run infinite garbage values and not what I wanted.
It is needed to print some spaces before printing the numbers in each row, and the number of spaces should be decreasing depending on the row:
int rows = 6;
for (int i = 1; i <= rows; ++i) {
for (int j = rows - i; j >= 1; j--) {
System.out.print(" ");
}
for (int j = 1; j <= i; ++j) {
System.out.print(j + " ");
}
System.out.println();
}
This prefix may be build using String::join + Collections::nCopies:
System.out.print(String.join("", Collections.nCopies(rows - i, " ")));
Or since Java 11, this prefix may be replaced using String::repeat:
System.out.print(" ".repeat(rows - i));
Instead of two nested for loops, you can use a single while loop with two incrementing variables. The number of iterations stays the same.
int n = 7, i = 0, j = 0;
while (i < n) {
// element
if (i + j >= n - 1) {
// print an element
System.out.print(i + j + 2 - n);
} else {
// print a whitespace
System.out.print(" ");
}
// suffix
if (j < n - 1) {
// print a delimiter
System.out.print(" ");
j++;
} else {
// print a new line
System.out.println();
j = 0;
i++;
}
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
See also: Optimized Bubble Sort
Your approach is almost correct - use two nested for loops, all that remains is to add one if else statement and calculate the sum of coordinates i and j.
Try it online!
public static void main(String[] args) {
int n = 6;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(" ");
int sum = i + j;
if (sum > n)
System.out.print(sum - n);
else
System.out.print(" ");
}
System.out.println();
}
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
See also: Printing a squares triangle. How to mirror numbers?
You can print an inverted triangle using two nested for-loops as follows:
// the number of rows and the
// number of elements in each row
int n = 6;
// iterating over rows with elements
for (int i = 0; i < n; i++) {
// iterating over elements in a row
for (int j = 0; j < n; j++) {
// element
if (i + j >= n - 1) {
// print an element
System.out.print(i + j + 2 - n);
} else {
// print a whitespace
System.out.print(" ");
}
// suffix
if (j < n - 1) {
// print a delimiter
System.out.print(" ");
} else {
// print a new line
System.out.println();
}
}
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
See also: How to draw a staircase with Java?
You have to print spaces before printing the numbers to make the triangle look inverted, the number of spaces depends on the amount of numbers you skip which are rows-i, so you can loop from i to rows and print space in each iteration.
int rows = 6;
for (int i = 1; i <= rows; ++i) {
for (int j = i; j < rows; j++) {
System.out.print(" ");
}
for (int j = 1; j <= i; ++j) {
System.out.print(j + " ");
}
System.out.println();
}
Output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
You can use the property that for the row containing i as the greatest number of the row the number of the spaces can be calculated as 2*(rows-i). You can rewrite your program like below:
public class Main {
public static void main(String[] args) {
int rows = 6;
for (int i = 1; i <= rows; ++i) {
for (int nspaces = 0; nspaces < 2 * (rows - i); ++nspaces) {
System.out.print(" ");
}
for (int j = i; j > 0; --j) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
Related
I need to know how to print out the following pattern:
5
4 5
3 4 5
2 3 4 5
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
Any and all help is appreciated.
What i have so far is this:
for (int i = 1; i <= num; i++)
{
for (int j = 1; j <= i; j++)
{
System.out.print(j+" ");
}
System.out.println();
}
for (int i = num-1; i >= 1; i--)
{
for (int j = 1; j <= i; j++)
{
System.out.print(j+" ");
}
System.out.println();
}
and it outputs this:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
So I have the structure of the pattern itself understood, but it seems that I need to reverse the flow somehow. This is what I do not understand.
Change the loop conditions as shown below:
public class Main {
public static void main(String[] args) {
int num = 5;
for (int i = num; i >= 1; i--) {// Start with num and go downwards up to 1
for (int j = i; j <= num; j++) {// Start with i and go upwards up to num
System.out.print(j + " ");
}
System.out.println();
}
for (int i = 2; i <= num; i++) {// Start with 2 and go downwards up to num
for (int j = i; j <= num; j++) {// Start with i and go downwards up to num
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output:
5
4 5
3 4 5
2 3 4 5
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
Accepted answer not output the corrent pattern so... this code works.
Ther are two loops, each one iterate line by line. First from 5 to 1, the second one from 2 to 5.
In every iteration (every line) will print next to the first number the following numbers.
int num = 5;
for(int i = num ; i > 0 ; i--){
System.out.print(i+" "); //Print the first number of the line
for(int j = 1; j <= num-i; j++){
//Print as extra number as line need (first line = 0 extra numbers,
//second line = 1 extra number...)
System.out.print((i+j)+" ");
}
System.out.println(); //New line
}
for (int i = 2; i <= num; i++) { //Print second part starting by 2
for (int j = i; j <= num; j++) { //Print extra numbers
System.out.print(j+" ");
}
System.out.println(); //New line
}
And the output is as expected:
5
4 5
3 4 5
2 3 4 5
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
I did this below but I didn't get it right,
int i = 1;
while(i <= 6){
for(int j = 1;j <= 6-i;j++){
System.out.print(" ");
}
for(int m = 1; m <= i; m++){
System.out.print(m + " ");
}
i++;
System.out.println();
}
I got this instead :
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
But I need guide on how to get this below,
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
while(i <= 6){
for(int j = 1; j <= 6 - i; j++){
System.out.print(" ");
}
for(int m = i-1; m > 1; m--){
System.out.print(m + " ");
}
for(int m = 1; m < i; m++){
System.out.print(m + " ");
}
i++;
System.out.println();
}
This should work for you, i just added / edited this part:
for(int m = i-1; m > 1; m--){
System.out.print(m + " ");
}
for(int m = 1; m < i; m++){
System.out.print(m + " ");
}
To let it count down again, and let it count up afterwards
This should do the trick, but it's important to understand what is going on:
public class Main {
public static void main(String[] args) {
for (int i = 0; i <= 6; i++) {
printRow(6, i);
}
}
public static void printRow(int highestValue, int rowValue) {
for (int i = 0; i < (highestValue - rowValue); i++) {
System.out.print(" ");
}
for (int i = rowValue; i >= 1; i--) {
System.out.print(i + " ");
}
for (int i = 2; i <= rowValue; i++) {
System.out.print(i + " ");
}
System.out.println();
}
}
The first loop pads the left side of the pyramid, as you have already done. The second loop counts down from the value of the row to 1, which is the center of the pyramid. The third loop counts back up from 2 to the value of the row. Note that for the first row, 2 will not be printed, because i = 2 is greater than rowValue, which is 1, so the loop is skipped.
Running this results in the following:
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
Note that a row starting with 6 is printed since I used the bounds you provided. If this is not what should be done (from your example output), I will leave that up to you on how to fix this. Pay attention to the name of the arguments in the printRow method to see why there is an extra row printed.
There you have my solution, little smarty solution with using absolute value, with notes why is what where
public static void printPyramid(int rows) {
// row counter
for (int i = 1; i <= rows; i++) {
// padding- size = rows - i
for (int j = 1; j <= rows - i; j++) {
// 2 spaces - char + space
System.out.print(" ");
}
// print numbers
for (int j = -i; j <= i; j++) {
// we want only once 1, and skip print zero
if (j == 0 || j == 1) {
continue;
}
// print absolute value
System.out.print(Math.abs(j) + " ");
}
// new row- println same as print("\n");
System.out.println();
}
}
With 6 rows, output is
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
Let's break this down into parts. First we need to figure out how to output a single level of the pyramid. Let's start without padding. For the first level it's just "1", for every other level it's the level above it surrounded by the "number" of that level (and the spaces).
private static String buildLevel(int num) {
if (num == 1) return "1";
return Integer.toString(num) + " " + buildLevel(num -1) + " " + Integer.toString(num);
}
We then need to be able to add the padding, so let's create a method that pads to a certain length.
private static String pad(String stringToPad, int padTo) {
return String.join("", Collections.nCopies(padTo - stringToPad.length(), " ")) + stringToPad;
}
Putting this together we can create a method to build a pyramid by looping over the needed levels and concatenating the levels together.
private static String buildPyramid(int height) {
int expectedLength = height * 2 + 1;
String out = "";
for (int i = 1; i <= height; i++) {
out += pad(buildLevel(i), expectedLength) + "\n";
expectedLength += 2;
}
return out;
}
The length of the first line is the height * 2 + 1, derived by counting. (This includes two spaces at the beginning of each line, which is in your examples). Each subsequent line should be 2 longer than the one above it.
Call it like this to produce your example
public static void main(String[] args) {
System.out.println(buildPyramid(5));
}
Outputs:
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
For completeness, here is all the code in one block.
private static String buildLevel(int num) {
if (num == 1) return "1";
return Integer.toString(num) + " " + buildLevel(num -1) + " " + Integer.toString(num);
}
private static String pad(String stringToPad, int padTo) {
return String.join("", Collections.nCopies(padTo - stringToPad.length(), " ")) + stringToPad;
}
private static String buildPyramid(int height) {
int expectedLength = height * 2 + 1;
String out = "";
for (int i = 1; i <= height; i++) {
out += pad(buildLevel(i), expectedLength) + "\n";
expectedLength += 2;
}
return out;
}
public static void main(String[] args) {
System.out.println(buildPyramid(6));
}
Its easy enough to rotate numbers to the left. I would do the following:
int numberCount = 4;
int rotationCount = 2 * numberCount;
for(int i = 0; i < rotationCount; i++)
{
for(int j = 0; j < numberCount; j++)
{
System.out.print((i+j) % numberCount + " ");
}
System.out.println();
}
In this example the following would be printed:
0 1 2 3
1 2 3 0
2 3 0 1
3 0 1 2
0 1 2 3
1 2 3 0
2 3 0 1
3 0 1 2
How would you do the same thing, but rotating the numbers to the right?
The answer was obvious once I thought about it-- to move a number left, you add to it, so to move right, you subtract from it. I thought the formula would be significantly changed, so I was thinking of formulas that were much more complicated than the solution turned out to be.
// ensures mod is positive
int mod(int a, int b)
{ return (a%b+b)%b; }
int numberCount = 4;
int rotationCount = 2 * numberCount;
for(int i = 0; i < rotationCount; i++)
{
for(int j = 0; j < numberCount; j++)
{
System.out.print(mod((j-i), numberCount) + " ");
}
System.out.println();
}
I need to draw a numeric diamond, for example with a height of 9:
1
222
33333
4444444
555555555
4444444
33333
222
1
I wrote the code and I managed to get the same diamond, but with stars. I want it with these numbers. How can I do that? Here is what I have done so far:
for (int i = 1; i < 10; i += 2) {
for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print("a");
System.out.print("\n");
}
for (int i = 7; i > 0; i -= 2) {
for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print("b");
System.out.print("\n");
}
Regarding your code:
System.out.print("\n"); should be replaced by System.out.println().
You should a dynamic height instead of hard-coding 9.
It prints the correct pattern, only what is printed is wrong: instead of printing "a" and "b", you should print the index of the loop and see what you can get from there. This is #Tsung-Ting Kuo solution.
You can do it with fewer loops and a more understandable in my view. Consider the following algorithm:
For each row of the pattern (so the row goes from 0 to height excluded)
For each column of the pattern (so the column goes from 0 to height excluded)
We need to print a space when we are in the upper-right, upper-left, lower-right or lower-left of the diagram.
Upper-left: This is when the column is less than height/2-row-1
Lower-left: This is when the column is less than row-height/2
Factoring these two expressions in a single one, this is when the column is less than height/2 - min where min = Math.min(row+1, height-row).
Upper-right: This is when the column is greater than height/2+row+1
Lower-right: This is when the column is greater than height/2+height-row
Factoring these two expressions in a single one, this is when the column is greater than height/2 + min where min = Math.min(row+1, height-row).
Otherwise, we need to print Math.min(row+1, height-row).
Turning into code:
public static void main(String[] args) {
int height = 9;
for (int row = 0; row < height; row++) {
for (int column = 0; column < height; column++) {
int min = Math.min(row+1, height-row);
if (column <= height / 2 - min || column >= height / 2 + min) {
System.out.print(" ");
} else {
System.out.print(min);
}
}
System.out.println();
}
}
Sample output:
1
222
33333
4444444
555555555
4444444
33333
222
1
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) {
final int MID_ROW_NUM = 5;
for (int i = 1 - MID_ROW_NUM; i < MID_ROW_NUM; i++) {
int x = Math.abs(i);
System.out.println(" ".repeat(x) + String.valueOf(MID_ROW_NUM - x).repeat((MID_ROW_NUM - x) * 2 - 1));
}
}
}
Output:
1
222
33333
4444444
555555555
4444444
33333
222
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) {
final int MID_ROW_NUM = 5;
for (int i = 1 - MID_ROW_NUM; i < MID_ROW_NUM; i++) {
int x = Math.abs(i);
System.out.println(" ".repeat(x) + ((MID_ROW_NUM - x) + " ").repeat((MID_ROW_NUM - x) * 2 - 1));
}
}
}
Output:
1
2 2 2
3 3 3 3 3
4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5
4 4 4 4 4 4 4
3 3 3 3 3
2 2 2
1
Please try the following code (I have tested it), only change two print:
public static void main(String[] args) throws Exception {
for (int i = 1; i < 10; i += 2) {
for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print(i/2+1); // Change here
System.out.print("\n");
}
for (int i = 7; i > 0; i -= 2) {
for (int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for (int j = 0; j < i; j++)
System.out.print(i/2+1); // Change here
System.out.print("\n");
}
}
Output:
1
222
33333
4444444
555555555
4444444
33333
222
1
You can draw a numeric rhombus using IntStream as follows:
int m = 5;
int n = 5;
String[][] arr = IntStream
.rangeClosed(-m, m)
.map(Math::abs)
.mapToObj(i -> IntStream
.rangeClosed(-n, n)
.map(Math::abs)
.mapToObj(j -> i + j > Math.max(m, n) ? " " : "" + (m - i))
.toArray(String[]::new))
.toArray(String[][]::new);
// formatted output
Arrays.stream(arr).map(row -> String.join(" ", row)).forEach(System.out::println);
0
1 1 1
2 2 2 2 2
3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5 5 5
4 4 4 4 4 4 4 4 4
3 3 3 3 3 3 3
2 2 2 2 2
1 1 1
0
See also: Filling a 2d array with numbers in a rhombus form • Print this diamond
I'm supposed to have four patterns in a single program but the program won't output anything past my 2nd for statement. Can someone take a look at this please? Line RIGHT after Pattern C is where it stops outputting.
import java.util.Scanner;
public class Patterns
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a positive maximum integer value: ");
int max = input.nextInt();
//1st Pattern
System.out.println("\nPattern A: ");
for (int i = 1; i <= max; i++){
for (int j = 1; j <= i; j++){
System.out.print(j + " ");
}
System.out.println();
}
//2nd Pattern
System.out.println("\nPattern B:");
for (int i = -5; i <= max; i++, max--){
for (int j = 1; j <= max; j++){
System.out.print(j + " ");
}
System.out.println();
}
// 3rd pattern and WHERE PROBLEM STARTS!!
System.out.println("\nPattern C:");
for (int i = 0; i < max; i++){
for (int j = i; j < 0; j++){
System.out.print(j + " ");
}
System.out.println();
}
}
}
Are my loops nested improperly?
My program asks the user for a max integer and makes a program based on that
here are some sample outputs
Enter a positive maximum integer value: 6
Pattern A:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
Pattern B:
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Pattern C:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1
Pattern D:
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
for (int i = 0; i < max; i++){
for (int j = i; j < 0; j++){
i and j both start off at 0. 0 can never be less than 0, so your j loop will never execute.
The other issue is that you're reusing the max variable after Pattern B has altered the value of it. You should copy the value of max into a variable that you can modify within the pattern without affecting the original.
For Pattern C, the loop is not executing because of your conditional and the fact that you've altered max.
Swap B and C with this.
//2nd Pattern
System.out.println("\nPattern B:");
int patternBMax = max;
for (int i = -5; i <= patternBMax; i++, patternBMax--)
{
for (int j = 1; j <= patternBMax; j++)
{
System.out.print(j + " ");
}
System.out.println();
}
// 3rd pattern and WHERE PROBLEM STARTS!!
System.out.println("\nPattern C:");
int patternCMax = max;
for (int i = 1; i <= patternCMax; i++)
{
// Pad the output with the necessary whitespace
for (int j = 0; j < patternCMax - i; j++)
{
System.out.print(" ");
}
for (int k = i; k > 0; k--)
{
System.out.print(k + " ");
}
System.out.println();
}
and you should get this
Pattern B:
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
Pattern C:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
6 5 4 3 2 1