I have to create a method that results as below:
for n = 5
* 2 3 4 5
* * 3 4 5
* * * 4 5
* * * * 5
* * * * *
My attempt:
int n = 5;
for (int i = 0; i < n; i++) {
String row = "";
for (int j = 0; j < n; j++) {
row += "*";
if (i==j) {
System.out.print(row + "\n");
}
}
}
}
Result is:
*
**
***
****
*****
Anna, you should do something like this:
int n = 5;
for (int i = 0; i < n; i++) {
String row = "";
//This for build the entire output var
for (int j = 0; j < n; j++) {
if (i<j) { // if you are behind or in the line it receive a "*"
row+=String.valueOf(j+1);
} else { //if you are not it receive the number wich is j+1
row += "*";
}
}
System.out.println(row + "\n"); //Print the entire line
}
In your implementation you was printing only in the match line, and never printing anything else in the first iteration loop.
Is it clear for you?
It sounds like you're trying to solve a quiz.
What you're looking for is a pattern to that grid, and your answer isn't too far off.
Looking back at your original sample:
When X (horizontal) is greater than Y (vertical) we print X, otherwise we print an asterisk. And there's a space in between each element.
public class Main9 {
for (int i = 0; i < n; i++) {
String row = "";
for (int j = 0; j < n; j++) {
if (i > j) {
// Now we should append X (or i in this case) to the row
// Adding 1 to the base 0 integer
// and appending with a space
row += (i+1)+" ";
} else {
// Otherwise just add "* "
row += "* ";
}
}
// Now that we're done with the j-loop we can print out the row
System.out.println(row);
}
}
You could do it without any string concatenation and not using other objects. Let me offer my soulution:
int n = 5;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
System.out.print(j <= i ? "*" : ("" + (j + 1)));
System.out.println();
}
Related
This question already has answers here:
How to make a diamond using nested for loops
(19 answers)
Closed 2 years ago.
I currently have this code which allows me to create the left half of the diamond shape. Is there any way to mirror it to complete the right half. Or a completely different way of creating this shape.
public class diamond {
int size = 0; //sets a starting value for size
static int length = 9;
public static void main(String[] args) {
//creates half of our diamond shape :(
for (int i = 0; i < length; i++) {
int j = length - 1 - i;
for (int k = length / 2; k < length; k++) {
if (k == i || k == j || k == length + 7 + i - j)
System.out.print("X");
else
System.out.print(" ");
}
System.out.println("");
}
}
}
Here is another alternative that takes a slightly different approach.
Since certain widths or lines can't be specified exactly and always have a single middle line, this just prompts for a number.
It calculates spacing and adjusts the field of asterisks within two loops. The first does the top and middle line. The second just does the bottom portion.
String symb = "*";
Scanner input = new Scanner(System.in);
int max = 0;
while (max <= 1) {
System.out.print("Enter a positive no > 1: ");
max = input.nextInt();
}
System.out.println("Width and height are " + (2*max -3)+"\n");
for (int i = 1; i < max; i++) {
System.out.println(" ".repeat(max - i) + symb);
symb += "**";
}
for (int i = 2; i < max; i++) {
System.out
.println(" ".repeat(i) + symb.substring(2 * i));
}
When prompted for and provided an input of 5, this prints.
Enter a positive no > 1: 5
Width and height are 7
*
***
*****
*******
*****
***
*
You can modify this to produce the type of diamond you want.
Below code prints the diamond pattern as per your diagram. This program allows the user to input the no of rows for the diamond and also allows the user to select any shape you want to create your diamond with.
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
int n, i, j, space = 1;
System.out.print("Enter the number of rows: ");
Scanner s = new Scanner(System.in);
n = s.nextInt();
System.out.print("Enter Symbol : ");
char c = s.next().charAt(0);
drawDiamond(n,c);
}
static void drawDiamond(int n, char c) {
int i, j, space, k = 0;
for (i = 1; i <= n; i++) {
for (j = 1; j <= n - i; j++) {
System.out.print(" ");
}
while (k != (2 * i - 1)) {
if (k == 0 || k == 2 * i - 2)
System.out.print(c);
else
System.out.print(" ");
k++;
}
k = 0;
System.out.println();
}
n--;
for (i = n; i >= 1; i--) {
for (j = 0; j <= n - i; j++) {
System.out.print(" ");
}
k = 0;
while (k != (2 * i - 1)) {
if (k == 0 || k == 2 * i - 2)
System.out.print(c);
else
System.out.print(" ");
k++;
}
System.out.println();
}
}
}
Sample Output :
Enter the number of rows: 4
Enter Symbol : *
*
* *
* *
* *
* *
* *
*
This Code draws a diamond like your picture but only works with odd numbers.
class Diamond{
int size = 0;
static int length = 9;
public static void main(String[] args) {
int outerSpace = length / 2; //number left to the first x
int count = outerSpace; //same number used to find the mid
int up = 0; //counter for the space between the xx
for (int i = 0; i < length; i++) {
if (i < count) { //this code gets used till you reach the middle
for (int j = 0; j < outerSpace; j++) { //prints space left of x
System.out.print(" ");
}
System.out.print("X");
for (int k = 0; k < up; k++) {
System.out.print(" "); //prints space between the x
}
System.out.println("X");
outerSpace--;
up += 2;
}else{ //code after middle
for (int j = 0; j < outerSpace; j++) {
System.out.print(" ");
}
System.out.print("X");
for (int k = 0; k < up; k++) {
System.out.print(" ");
}
System.out.println("X");
outerSpace++;
up -= 2;
}
}
}
}
To get the exact same design, The input length has to be even number.
public class Main {
private static int legnth = 10;
private static int x = legnth /2;
private static int y = x + 1;
public static void main(String[] args) {
for(int i=1; i <= legnth/2; i++) {
for(int j=1; j <= legnth; j++) {
if(j==x || j==y) {
System.out.print("*");
}else {
System.out.print(" ");
}
}
x--;
y++;
System.out.println("");
}
x+=2;
y-=2;
for(int i=1; i < legnth/2; i++) {
for(int j=1; j < legnth; j++) {
if(j==x || j==y) {
System.out.print("*");
}else {
System.out.print(" ");
}
}
x++;
y--;
System.out.println("");
}
}
}
output
**
* *
* *
* *
* *
* *
* *
* *
**
Here is another solution where you can create a string array for one fourth of the diamond and later manipulate that array to print it into diamond. It can take even or odd both to create a diamond like shape.
static int length=9;
static int n=length/2;
public static void main(String[] args) {
String []arr = new String[n];
for (int i = 0; i < n; i++) {
String space="";
int j = n - i;
for (int k = 0; k < j; k++) {
space=space+" ";
}
arr[i]=space+"X";
}
// To print upper half of diamond
for(int i=0;i<n;i++) {
String upper= arr[i] + arr[n -1 -i].substring(0,arr[n-1-i].length()-2)
+ arr[n -1 -i].substring(1,arr[n -1 -i].length());
System.out.println(upper);
}
// To print middle of the diamond
System.out.println("X" + arr[0].substring(0,arr[0].length()-1)
+arr[0].substring(0,arr[0].length()-1) + "X");
// To print down half of the diamond
for(int i=0;i<n;i++) {
String down= arr[n -1 -i]+arr[i].substring(0,arr[i].length()-2)
+arr[i].substring(1,arr[i].length());
System.out.println(down);
}
}
Here is another solution. It will work for any valid odd integer value given for length.
void createDiamond(int length) {
int n = length / 2;
for (int i = 0; i < length; i++) {
for (int j = 0; j <= length; j++) {
if ((i >= 0 && i <= n && (j == n - i || j == n + 1 + i))
|| (i > n && i < length && (j == i - n || j == length + n - i)))
System.out.print("X");
else
System.out.print(" ");
}
System.out.println();
}
}
Output:
createDiamond(9);
XX
X X
X X
X X
X X
X X
X X
X X
XX
This question already has answers here:
Java algorithm to make a straight pyramid [closed]
(4 answers)
Closed 3 years ago.
I need to write a code for pyramid pattern with asterisks. yeah, it sounds like the codes on everywhere. but, i need to make a pyramid with a number of asterisks, not a number of rows.
for example, if user gave 9, then need to print a pyramid until the asterisks runs out. It should be center pyramids.
I've tried with the number of rows. but i have no idea how to print with the number of asterisks. while loop could be my answer, but i'm not sure..
public static void main(String args[]) {
int n = 5; // number of rows
for (int i = 0; i < n; i++)
{
for (int j = n - i; j > 1; j--)
{
System.out.print(" ");
}
for (int j = 0; j <= i; j++)
{
System.out.print("* ");
}
System.out.println();
}
}
the result should be like this, but without space between asterisks..
*
* *
* * *
* * * *
* * * * *
my output is showing exactly same thing, but i'm using a number of rows, not number of asterisks.
Not an optimal solution, but you set a maximum number of rows with n=100.
Then you define your asterix number to break out of nested loop. ctr is the total number of asterix.
It goes until desired number asterix reached, checking ctr value.
int n = 100;
int ctr = 0;
int asterix = 5;
for (int i = 0; i < n; i++)
{
for (int j = n - i; j > 1; j--)
{
System.out.print(" ");
}
for (int j = 0; j <= i; j++)
{
ctr++;
System.out.print("* ");
if(ctr == asterix ){
i=j=n;
}
}
System.out.println();
}
}
Based on #Hans Kesting's idea.
public static void main(String args[]) {
int n = 5; // number of asterisks
int max = (int)((1+Math.sqrt(1+8*n))/2);
for (int i = 0; i < n; i++)
{
for (int j = max - i; j > 1; j--)
{
System.out.print(" ");
}
for (int j = 0; j <= i; j++)
{
System.out.print("* ");
--n;
}
System.out.println();
}
}
I'm missing by just a little bit. What I want:
*******
*****
***
*
***
*****
*******
What I'm getting
*******
*****
***
*
*
***
*****
*******
The code
public class HD404 {
public static void main(String[] args) {
int N = StdIn.readInt();
int x = N*2-1;
for (int i = 0; i < N; i++) {
for (int j = i; j > 0; j--) {
StdOut.print(" ");
}
for (int k = 0; k < x; k++) {
StdOut.print("*");
}
x-=2;
StdOut.println();
}
x = 1;
for (int i = 0; i < N; i++) {
for (int j = i; j < N-1; j++) {
StdOut.print(" ");
}
for (int k = 0; k < x; k++) {
StdOut.print("*");
}
x += 2;
StdOut.println();
}
}
}
Right now I'm mostly just guessing and I just can't pin point my error. What am I missing here?
The problems lays with the second part of your code where you ask to draw one star and you start at zero where you should start at one.
Solution
x = 1;
for (int i = 0; i < N; i++)
should be replaced with
x = 3;
for (int i = 1; i < N; i++)
The problem is that you are starting to draw the bottom of the hourglass with 1 asterisk (x = 1) instead of 3.
The second issue is that the bottom of the hourglass only has N-2 lines, not N-1 so the loop should start at 1 instead of 0. This is because the line with a single asterisk was already drawn in the upper-half.
Corrected code:
public static void main(String[] args) {
int N = StdIn.readInt();
int x = N*2-1;
for (int i = 0; i < N; i++) {
for (int j = i; j > 0; j--) {
StdOut.print(" ");
}
for (int k = 0; k < x; k++) {
StdOut.print("*");
}
x-=2;
StdOut.println();
}
x = 3; // <-- not 1 here, the first line has 3 asterisks
for (int i = 1; i < N; i++) { // <-- i starts at 1 because the first line was already drawn in the upper half
for (int j = i; j < N-1; j++) {
StdOut.print(" ");
}
for (int k = 0; k < x; k++) {
StdOut.print("*");
}
x += 2;
StdOut.println();
}
}
As a side-note, you could rewrite this code a lot shorter by making the following observations:
There are x lines to draw so we can loop from 0 to x included (to respect the symmetry) and skip the middle line so as not to draw it twice
For every line, there are x columns to draw and it is either a space or a *.
For every line, * is drawn only if the current column is between min(i, x-i) and max(i, x-i) (if we're in the upper-part, i < x-i and if we're in the bottom-part, i > x-i).
Code:
public static void main(String[] args) {
int N = 4;
int x = 2 * N - 1;
for (int i = 0; i <= x; i++) {
if (i == N) continue; // skip the middle-line for it not to be drawn twice
for (int j = 0; j < x; j++) {
System.out.print(j >= Math.min(i, x-i) && j < Math.max(i, x-i) ? "*" : " ");
}
System.out.println();
}
}
Sample output:
*******
*****
***
*
***
*****
*******
The easiest way I can think up is probably to prevent the last iteration of your first outer loop, that way you'll prevent the first single star line to be shown.
I would probably do it this way:
for(int i = 0; i < N && x > 1; i++)
{
/*Code of the first inner loop*/
}
For those whose still looking for a simpler and lesser code regarding hourglass challenge. This contains 2 for loops only.
You may use this as reference.
public static void hourGlass(int size) {
// 2 for loops only
int dimension = (size * 2) - 1, space = 0, stars = size - 1, printed = 0;
for(int i=0; i<dimension; i++) {
int actual = space;
for (int j=dimension; j > 0; j--) {
if(actual > 0) {
System.out.print(" ");
actual--;
}
else {
System.out.print("*");
if(stars==printed) {
actual = space;
printed = 0;
} else {
actual = 1;
printed++;
}
}
}
if(i <= size-2) { // will pattern spaces and stars from top to middle
space++;
stars--;
}
else { // will pattern spaces and stars from middle to top
space--;
stars++;
}
System.out.println();
}
}
I'm practicing basic coding exercises and trying to print the following triangle in Java:
*
***
*****
***
*
The following code gives me the results but I feel like there must be a much more elegant solution
for (int i = 1; i <= 5; i++) {
if (i % 2 == 1) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println("");
}
}
for (int i = 3; i > 0; i--) {
if (i % 2 == 1) {
for (int j = 1; j < i + 1; j++) {
System.out.print("*");
}
System.out.println("");
}
}
Can anyone provide some insight into how to make this work in a better way?
Ok, here's some more code that produces the correct result that uses just the two for loops, but it looks even uglier:
for (int i = 1; i <= 10; i += 2) {
if (i <= 5) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println("");
}
else if(i > 5 && i < 8){
for(int j = i/2; j > 0; j--){
System.out.print("*");
}
System.out.println("");
}
else{
for(int j = 1; j > 0; j--){
System.out.print("*");
}
System.out.println("");
}
}
First, you are skipping each 2nd iteration of the loop because you want to increase two steps at once. You can do this by changing the "i++" in your loop to "i += 2" and "i--" to "i -= 2", that will have the same effect and allows you to remove the if inside both loops.
Another improvement would be using a single outer loop and figuring out whether the inner loop should be increasing or decreasing the amount of asterisks. Maybe you can come up with an equation that gives you the amount of asterisks based on the value of i? (I didn't want to solve it completely so you have some exercise left, just comment if you want a full solution)
Updated with a solution that might be considered elegant as you can change the height of the triangle and there is no repetition:
int height = 5;
for (int i = 1; i <= 2 * height; i += 2) {
int numAsterisks;
if (i <= height) {
numAsterisks = i;
} else {
numAsterisks = 2 * height - i;
}
for (int j = 0; j < numAsterisks; j++) {
System.out.print("*");
}
System.out.println();
}
What about the following?
public void printTriangle(int size) {
int half = size / 2;
for (int i = 0; i < size; i++) {
int stars = 1 + 2 * (i <= half ? i : size - 1 - i);
char[] a = new char[stars];
Arrays.fill(a, '*');
System.out.println(new String(a));
}
}
Or just a bit more optimized:
public void printTriangle(int size) {
int half = size / 2;
char[] a = new char[size];
Arrays.fill(a, '*');
for (int i = 0; i < size; i++) {
int stars = 1 + 2 * (i <= half ? i : size - 1 - i);
System.out.println(new String(a, 0, stars));
}
}
for(int i = 0; i < 7; i++) {
for(int j = 0; j < i; j++) {
print("*");
}
print("\n");
}
This can be another solution to print a regular right triangle...
Here's a different way of looking at the problem. By using an integer array, I can solve lots of shape drawing problems by changing the values in the array.
When solving more difficult problems, you would use model classes instead of simple integers. The idea, however, is the same.
Here's the output.
*
***
*****
***
*
And here's the code:
public class Triangle {
public static void main(String[] args) {
int[] heights = {1, 3, 5, 3, 1};
for (int i = 0; i < heights.length; i++) {
for (int j = 0; j < heights[i]; j++) {
System.out.print("*");
}
System.out.println("");
}
}
}
How about...
int width = 5;
for (int i = 1; i <= width; i+=2){
System.out.println(String.format("%"+i+"s", "").replaceAll(" ", "*"));
}
for (int i = width-2; i > 0; i-=2){
System.out.println(String.format("%"+i+"s", "").replaceAll(" ", "*"));
}
Or, even better yet...
int width = 7;
double half = width / 2
for (int i = 0; i < width; i++){
System.out.println(String.format("%"+((i < half ? i : (width-i-1))*2+1)+"s", "").replaceAll(" ", "*"));
}
Gives
*
***
*****
***
*
My professor wants me to print out the matrices side by side with the "+" between the two matrices and then a "=" sign. In the end he wants us to add the matrices together.
This is the work so far.
So the result would come out as:
1 2 3 9 8 7 10 10 10
4 5 6 + 6 5 4 = 10 10 10
7 8 9 3 2 1 10 10 10
enter code here public static void main(String[] args) {
int matrix1[][] = {{1,2,3},{4,5,6},{6,7,8}};
int matrix2[][] = {{9,8,7},{6,5,4},{3,2,1}};
int result1;
int[][] result2 = new int[2][3];
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[0].length; j++) {
System.out.printf(matrix1[i][j] + " ");
System.out.print("");
}
System.out.println("");
}
for (int i = 0; i < matrix2.length; i++) {
for (int j = 0; j < matrix2[0].length; j++) {
System.out.printf(matrix2[i][j] + " ");
}
System.out.println("");
}
}
My problem is, how could I print it side by side with the solutions?
Consider the two printing loops for your matrices:
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[0].length; j++) {
System.out.printf(matrix1[i][j] + " ");
}
System.out.println("");
}
for (int i = 0; i < matrix2.length; i++) {
for (int j = 0; j < matrix2[0].length; j++) {
System.out.printf(matrix2[i][j] + " ");
}
System.out.println("");
}
They print matrix 1, then 2 - and so the matrices will be below each other.
If you want the matrices side by side, you need to print line 1 of every matrix, then - after a new line - line 2 of every matrix, etc. By re-arranging how the loops go through the matrices, you could have your new layout.
You unfortunately cannot print them one at a time, you need to take it row by row. This solution requires both matrix1 and matrix2 to be of equal height. But here's a template that should get you started.
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[i].length; j++) {
}
if (i == matrix1/2) {
} else { //One part of if handles when "+" is needed, other one doesn't
}
for (int j = 0; j < matrix2[i].length; j++) {
}
if (i == matrix1/2) {
}
for (int j = 0; j < ???; j++) {
}
}