how to print this pattern in java i have no idea how - java

i cant print this pattern :
1 2 3 4 *
1 0 0 * 5
1 0 * 0 5
1 * 0 0 5
* 2 3 4 5
i tried to print but only on row :
public class Pattern {
public static void main(String[] args) {
for(int j=1;j<=5;j++)
{
if(j>4) {
System.out.print("*");
}
else {
System.out.print(j);
}
}
}
}

Let's try to consider the logic of this output:
You have an NxN matrix, with rows and columns numbered 1..N.
If you're on the secondary diagonal (i.e. row+column=N+1), print a *
Else, if you're on the borders (i.e., either the row or the column is 1 or N), print the column number
Else, print a 0
Now, you just need to convert this logic to Java:
int size = 5;
for (int i = 1; i <= size; ++i) {
for (int j = 1; j <= size; ++j) {
char ch;
if (i + j == size + 1) {
ch = '*';
} else if (i == 1 || i == size || j == 1 || j == size) {
ch = (char) ('0' + j);
} else {
ch = '0';
}
System.out.print(ch + " ");
}
System.out.println();
}

Related

How to print a 2D array in java

Hello so am trying to create a 2D array of int with random number of rows and columns and a random starting and ending points using java to apply the A* algorithm on it.
When i add {S} and {E} to define the tow points and print it there are numbers outside of the 2D array printed.
`Random rand = new Random();
int min = 2, max = 10;
// a random number of rows and columns
int a = (int)(Math.random() * (max - min + 1)) + min;
// the location of the starting point.
int row_start = rand.nextInt(a);
int col_start = rand.nextInt(a);
// the location of the ending point.
int row_end = rand.nextInt(a);
int col_end = rand.nextInt(a);
int [][] M = new int [a][a];
public void create() {
//empty: 0; grass: 1; sand: 2; water: 3; wall: 4.
for (int i = 0; i < a; i++) {
for (int j = 0; j < a; j++) {
M[i][j] = rand.nextInt(5);
}
}
for (int i = 0; i < a; i++) {
for (int j = 0; j < a; j++) {
System.out.print(" " +M[i][j] + "\t");
if(row_start == i && col_start == j) {
System.out.print("{S}" + "\t");
}
if(row_end == i && col_end == j) {
System.out.print("{E}" + "\t");
}
}
System.out.print("\n");
}
}`
the output looks like this:
1 0 4 0
2 {S} 1 2 2
4 4 {E} 0 3
2 0 3 3
the 2 and 3 shouldn't appear there.
The problem is that you always print m[i][j].
What you need is to only print m[i][j] when i and j are not S and E positions. When i and j are S and E positions, print S or E. Otherwise, print m[i][j].
if(row_start == i && col_start == j) {
System.out.print("{S}" + "\t");
} else if(row_end == i && col_end == j) {
System.out.print("{E}" + "\t");
} else {
System.out.print(" " +M[i][j] + "\t");
}

Invert incrementing triangle pattern

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

How do I print a half pyramid with numbers and stars together?

I'm trying to print a half pyramid with numbers and stars together and the output must be like this:
1 1 1 1 1 1 1
2 * * * * 2
3 * * * 3
4 * * 4
5 * 5
6 6
7
Here is the code that I've done so far:
public class numberplsustar {
public static void main(String[] args) {
int rows = 7, i, j, num;
for (i = rows; i >= 1; i--) {
for (j = 1; j <= i; ++j) {
if (i >= 3 && i <= 6) {
System.out.print("* ");
} else
System.out.print(i + " ");
}
System.out.println();
}
}
}
And this is the output:
7 7 7 7 7 7 7
* * * * * *
* * * * *
* * * *
* * *
2 2
1
The problem is you don't check for the first character and the last character to print the values. Also start printing from rows: 7.
You should start printing from 1 (j=1), than increment the value on each time j++.
You should check for which value to be printed on each step:
(i == rows || i == 2 || temp == 1) ? j : "*"
prints j (number) :
i == rows : for the first row (1 1 1 1 1 1 1)
i == 2 : for the row before the last one (6 6)
temp == 1 : for the numbers at the end of rows
otherwise prints *
Try this:
public static void main(String[] args) {
int rows = 7;
for (int i = rows, j = 1; i > 0; i--, j++) {
System.out.print(j);
for (int temp = i - 1; temp > 0; temp--) {
System.out.print(" " + ((i == rows || i == 2 || temp == 1) ? j : "*"));
}
System.out.print("\n");
}
}
Output:
1 1 1 1 1 1 1
2 * * * * 2
3 * * * 3
4 * * 4
5 * 5
6 6
7
PS: In Java the first letter of class names should be capitalized according to naming conventions.
just print every characterindividualy and if its on the outline you print the number
public class piramid {
public static void main(String[] args) {
int n = 7;
for (int i=1; i<n; i++) {
for (int x=n; x>i; x--) {
if (i == 1 || x == n || x==i+1) {
System.out.print(i);
}
else {
System.out.print("*");
}
System.out.print(" ");
}
System.out.println("");
}
}
}
this code outputs this
1 1 1 1 1 1
2 * * * 2
3 * * 3
4 * 4
5 5
6
in response to your comment:
this would work:
public class piramid {
public static void main(String[] args) {
int n = 7;
for (int i=1; i<n; i++) {
for (int x=0; x<i; x++) {
if (i == n-1 || x == 0|| x == i-1) {
System.out.print(i);
}
else {
System.out.print("*");
}
System.out.print(" ");
}
System.out.println("");
}
}
}
and the output is
1
2 2
3 * 3
4 * * 4
5 * * * 5
6 6 6 6 6 6
Solution
Check if i == 1(first) row -> print i
Check if j is at the edge j==i || j == range -> print i
else print "*"
public static void main(String[] args) {
int range = 7;
for(int i = 1; i <= range; i++){
for(int j = range; j >= i ; j--){
if(i == 1){
System.out.print(i);
}else if(j == range || j == i){
System.out.print(i);
}else{
System.out.print("*");
}
}
System.out.println();
}
}
Outsputs
1 1 1 1 1 1 1
2 * * * * 2
3 * * * 3
4 * * 4
5 * 5
6 6
7
To print a triangle in some corner of a 2d array, you can use two nested for loops (or streams) and two nested conditional statements (or ternary operators). Your code might look something like this:
int m = 7;
IntStream.range(0, m)
.mapToObj(i -> IntStream.range(0, m)
// 'i' - row, 'j' - column
.mapToObj(j ->
// triangle corner:
// upper left: 'i + j < m'
// lower right: 'i + j >= m - 1'
// lower left: 'i >= j'
// upper right: 'i <= j'
i + j >= m - 1 ?
// triangle boundaries:
// top: 'i == 0'
// bottom: 'i == m - 1'
// left: 'j == 0'
// right: 'j == m - 1'
// primary diagonal: 'i == j'
// secondary diagonal: 'i + j == m - 1'
i == m - 1 || j == m - 1 || i + j == m - 1 ?
// row number
(i + 1) + " "
// otherwise asterisk
: "* "
// otherwise whitespace
: " ")
// collect into one line
.collect(Collectors.joining()).stripTrailing())
// print line by line
.forEach(System.out::println);
Output:
1
2 2
3 * 3
4 * * 4
5 * * * 5
6 * * * * 6
7 7 7 7 7 7 7
int m = 7;
for (int i = 0; i < m; i++) {
String row = "";
for (int j = 0; j < m; j++) {
if (i <= j) {
if (i == 0 || j == m - 1 || i == j) {
row += (i + 1) + " ";
} else {
row += "* ";
}
} else {
row += " ";
}
}
System.out.println(row.stripTrailing());
}
Output:
1 1 1 1 1 1 1
2 * * * * 2
3 * * * 3
4 * * 4
5 * 5
6 6
7

How to print out an X using nested loops

I have searched through to find a simple solution to this problem.
I have a method called
printCross(int size,char display)
It accepts a size and prints an X with the char variable it receives of height and width of size.
The calling method printShape(int maxSize, char display) accepts the maximum size of the shape and goes in a loop, sending multiples of 2 to the printCross method until it gets to the maximum.
Here is my code but it is not giving me the desired outcome.
public static void drawShape(char display, int maxSize)
{
int currentSize = 2; //start at 2 and increase in multiples of 2 till maxSize
while(currentSize<=maxSize)
{
printCross(currentSize,display);
currentSize = currentSize + 2;//increment by multiples of 2
}
}
public static void printCross(int size, char display)
{
for (int row = 0; row<size; row++)
{
for (int col=0; col<size; col++)
{
if (row == col)
System.out.print(display);
if (row == 1 && col == 5)
System.out.print(display);
if (row == 2 && col == 4)
System.out.print(display);
if ( row == 4 && col == 2)
System.out.print(display);
if (row == 5 && col == 1)
System.out.print(display);
else
System.out.print(" ");
}
System.out.println();
}
}
Is it because I hardcoded the figures into the loop? I did a lot of math but unfortunately it's only this way that I have been slightly close to achieving my desired output.
If the printCross() method received a size of 5 for instance, the output should be like this:
x x
x x
x
x x
x x
Please I have spent weeks on this and seem to be going nowhere. Thanks
The first thing you have to do is to find relationships between indices. Let's say you have the square matrix of length size (size = 5 in the example):
0 1 2 3 4
0 x x
1 x x
2 x
3 x x
4 x x
What you can notice is that in the diagonal from (0,0) to (4,4), indices are the same (in the code this means row == col).
Also, you can notice that in the diagonal from (0,4) to (4,0) indices always sum up to 4, which is size - 1 (in the code this is row + col == size - 1).
So in the code, you will loop through rows and then through columns (nested loop). On each iteration you have to check if the conditions mentioned above are met. The logical OR (||) operator is used to avoid using two if statements.
Code:
public static void printCross(int size, char display)
{
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
if (row == col || row + col == size - 1) {
System.out.print(display);
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
Output: (size = 5, display = 'x')
x x
x x
x
x x
x x
Instead of giving a direct answer, I will give you some hints.
First, you are right to use nested for loops.
However as you noticed, you determine when to print 'x' for the case of 5.
Check that 'x' is printed if and only if row = col or row + col = size - 1
for your printCross method, try this:
public static void printCross(int size, char display) {
if( size <= 0 ) {
return;
}
for( int row = 0; row < size; row++ ) {
for( int col = 0; col < size; col++ ) {
if( col == row || col == size - row - 1) {
System.out.print(display);
}
else {
System.out.print(" ");
}
}
System.out.println();
}
}
ah, I got beaten to it xD
Here's a short, ugly solution which doesn't use any whitespace strings or nested looping.
public static void printCross(int size, char display) {
for (int i = 1, j = size; i <= size && j > 0; i++, j--) {
System.out.printf(
i < j ? "%" + i + "s" + "%" + (j - i) + "s%n"
: i > j ? "%" + j + "s" + "%" + (i - j) + "s%n"
: "%" + i + "s%n", //intersection
display, display
);
}
}
Lte's try this simple code to print cross pattern.
class CrossPattern {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter the number of rows=column");
int n = s.nextInt();
int i, j;
s.close();
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
if (j == i) {
System.out.print("*");
} else if (j == n - (i - 1)) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}

Creating a random colour grid with all adjacent colours different

So I have the following problem set to me: Write a program that takes an integer command-line argument N, and uses two nested for loops to print an N-by-N board that alternates between 6 colours randomly separated by spaces. The colours are denoted by letters (like 'r' for RED, 'b' for BLUE). You are not allowed to have two of the same colour next to eachother.
So, I know I probably need arrays to get around this problem. I tried several methods that all came up wrong. The following is one of my recent attempts, but I am unsure as how to now go through the grid and correct it. What the code does is make every row randomized with no colour left or right the same, but the columns are not fixed.
Note that I am a first year CS student with no programming history. I am guessing the solution to this problem isnt too complex, however, I cant see a simple solution...
int N = StdIn.readInt();
int array1[] = new int[N];
for (int column = 0; column < N; column++) {
int x = 0;
for (int row = 0; row < N; row++) {
int c = (int) (Math.random() * 6 + 1);
while (x == c) {
c = (int) (Math.random() * 6 + 1);
array1[row] = c;
}
if (c == 1) {
System.out.print("R ");
}
if (c == 2) {
System.out.print("O ");
}
if (c == 3) {
System.out.print("Y ");
}
if (c == 4) {
System.out.print("G ");
}
if (c == 5) {
System.out.print("B ");
}
if (c == 6) {
System.out.print("I ");
}
x = c;
}
System.out.println();
}
}
this was my solution for the problem. Quite convoluted though, but the logic behind it is straightforward. Each time you assign a new colour to your 2D array, you need only check the value of the array to the top and to the left of the position where you want to assign a new colour. You can only do this after you have assigned colours to the first row of the array however so you need to create separate conditions for the first row.
public class ColourGrid {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
char[][] clrGrid = new char[N][N];
char colours[] = {'r','b','y','w','o','g'} ;
for (int counter = 0 ; counter < N; counter++) {
for (int counter2 = 0 ; counter2 < N; counter2++) {
if (counter == 0 && counter2 == 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
else if (counter != 0 && counter2 == 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
while (clrGrid[counter][counter2] == clrGrid[(counter)-1][counter2]) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
else if (counter == 0 && counter2 != 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
while (clrGrid[counter][counter2] == clrGrid[(counter)][counter2-1]) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
else if (counter != 0 && counter2 != 0) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
while (clrGrid[counter][counter2] == clrGrid[(counter)-1][counter2] || clrGrid[counter][counter2] == clrGrid[counter][(counter2)-1]) {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
else {
clrGrid[counter][counter2] = colours[(int)(Math.random()* 5 + 1)] ;
}
}
}
for (int counter = 0 ; counter < N; counter++) {
System.out.println("");
for (int counter2 = 0 ; counter2 < N; counter2++) {
System.out.print(clrGrid[counter][counter2] + " ");
}
}
}
}

Categories