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();
}
Related
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
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 need series of for loops to return a box like below depending on the values of m & n.
Should output:
1 1 1 1 1 1 1
1 2 2 2 2 2 1
1 2 3 3 3 2 1
1 2 2 2 2 2 1
1 1 1 1 1 1 1
Below is my code so far which uses a series of loops to split the box in half and either ascends or descends the value for both the column and row. Where I am stuck is trying to find a way to make these perimeters for the values. Another note that this should be able to work without using any if statements.
int m = 5; //column value
int n = 7; //row value
int column;
for (int row = 0; row <= (m / 2); row++) {
//Ascending
for (column = 1; column < (n / 2); column++) {
int outputNumber = row + 1;
System.out.print(outputNumber + " ");
}
//Fixed
do {
int outputNumber = row + 1;
System.out.print(outputNumber + " ");
}
while (column < 0);
//Descending
for (column = n / 2; column >= 0; column--) {
int outputNumber = row + 1;
System.out.print(outputNumber + " ");
}
System.out.println();
}
for (int row = m / 2; row > 0; row--) {
for (column = 1; column <= n; column++) {
System.out.print(row + " ");
}
System.out.println();
}
Current output for the code above:
1 1 1 1 1 1 1
2 2 2 2 2 2 2
3 3 3 3 3 3 3
2 2 2 2 2 2 2
1 1 1 1 1 1 1
Here is my result. I know that it is a bit complicated and quick written, however it solves your problem. I also tested it with other numbers:
int m = 5; //column value
int n = 7; //row value
for (int i = 0; i < m / 2 + 1; i++) {
for (int j = 0; j < i + 1; j++) {
System.out.print(j + 1 + " ");
}
for (int j = 0; j < n - ((i + 1) * 2); j++) {
System.out.print(i + 1 + " ");
}
for (int j = 0; j < i + 1; j++) {
System.out.print(i + 1 - j + " ");
}
System.out.println("");
}
for (int i = m / 2 + 1; i < m; i++) {
for (int j = 0; j < m - i; j++) {
System.out.print(j + 1 + " ");
}
for(int j = 0; j < n - (m - i) * 2; j++) {
System.out.print(m-i + " ");
}
for(int j = 0; j < m - i; j++) {
System.out.print(m - i - j + " ");
}
System.out.println("");
}
Assuming my understanding is correct that the perimeter tiles should be 1, and subsequently each tile should display the minimum number of 'steps' it would take to get there from outside the matrix.
I personally have a hard time picturing/following your solution, so I'm not sure if my suggestion will mesh with your understanding.
First, lets separate the construction of this matrix from the printing of this matrix. I think this keeps things tidy, but that's my style.
Lets say you have c columns and r rows in your matrix. So we'll iterate over every cell with a nested for loop.
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
int distanceToEdgeOfRow = Math.abs(rows - (r - rows)); //this finds the number of steps to the nearest row end
int distanceToEdgeOfColumn = Math.abs(columns - (c - columns)); //this find the number of steps to the nearest column end
int shortestPath = Math.min(distanceToEdgeOfColumn, distanceToEdgeOfRow); //is it shorter to take the closest row exit or column exit?
//the shortestPath is still off by one, so we need to add 1 to shortestPath to see what should be printed on this tile
matrix[r][c] = shortestPath + 1;
}
}
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