How to print bowtie in java? - java

How to make this pattern if input N = 5 Output :
* *
** **
******
** **
* *
Here's my code
for(int i = 0; i < n + 1; i++) {
for(int j = 0; j < n + 1; j++) {
if ((j > i && j < n - i) || (j > (n-i) && j < i && i > n))
System.out.print(" ");
else
System.out.print("*");
}
System.out.println();
}
The result is like this:
* *
** **
******
******
******
******
How could I fix this?

You have used OR || to combine the upper down-pointing triangle of " " and the lower up-pointing triangle of " ". Good idea.
You describe the upper triangle as (j > i && j < n - i), that is correct.
However, you describe the lower triangle as (j > (n-i) && j < i && i > n).
That is where the problem is. The i > n is never true for i from 0 to n as in your outer loop construct. In order to describe the lower half of the pattern, you should have used i>n/2. You could have however dropped that part of the condition altogether, because the counter comparisons in the first part would only apply in the lower half anyway.
So (j > (n-i) && j < i).
That gets you:
* *
** **
******
******
** **
By the way, n lines, not n+1 lines in the outer loop.
As you can see, the lower triangle of " " is much too small. Both, to the right side and to the left side.
So you need to make your conditions more generous, i.e. "lower-equal" and "higher-equal" instead of "lower" and "higher". In code (j >= (n-i) && j <= i).
Putting it together:
public class Main {
static final int n = 5;
public static void main(String[] args)
{
for(int i = 0; i < n; i++) // only n lines
{
for(int j = 0; j < n+1; j++) {
if ((j > i && j < n - i) ||
(j >= (n-i) && j <= i)) // more generous and no second condition
System.out.print(" ");
else
System.out.print("*");
}
System.out.println();
}
}
}
This code is very similar to your attempt and gets you the desired
* *
** **
******
** **
* *

Your existing attempt is actually really close here is a working version which fixes the second condition (that in your current attempt would always be false):
class Main {
public static void main(String[] args) {
printBowtie(5);
}
private static void printBowtie(int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n + 1; j++) {
if ((j > i && j < n - i) || (j >= n - i && j <= i)) {
System.out.print(" ");
} else {
System.out.print("*");
}
}
System.out.println();
}
}
}
Output:
* *
** **
******
** **
* *
Relevant diff:
private static void printBowtie(int n) {
- for (int i = 0; i < n + 1; i++) {
+ for (int i = 0; i < n; i++) {
for (int j = 0; j < n + 1; j++) {
- if ((j > i && j < n - i) || (j > (n - i) && j < i && i > n)) {
+ if ((j > i && j < n - i) || (j >= n - i && j <= i)) {

You can simplify it greatly by putting the common code in a method as shown below:
public class Main {
static final int LINES = 5;
public static void main(String[] args) {
// Upper half
for (int line = 1; line <= LINES / 2 + 1; line++) {
print(line);
}
// Lower half
for (int line = LINES / 2; line >= 1; line--) {
print(line);
}
}
static void print(int line) {
for (int j = 1; j <= line; j++) {
System.out.print("*");
}
for (int j = 1; j <= LINES - 2 * line + 1; j++) {
System.out.print(" ");
}
for (int j = 1; j <= line; j++) {
System.out.print("*");
}
System.out.println();
}
}
Output:
* *
** **
******
** **
* *

Related

How to make diamond pattern using java?

How to make this pattern
if input N = 5
Output :
Mine is like this, it become 2N
if input N = 5
Output
Here's my code
int i,j;
for(i = 0; i <= n; i++)
{
for(j = 1; j <= n - i; j++)
System.out.print(" ");
for(j = 1; j <= 2 * i - 1; j++)
System.out.print("*");
System.out.print("\n");
}
for(i = n - 1; i >= 1; i--)
{
for(j = 1; j <= n - i; j++)
System.out.print(" ");
for(j = 1; j <= 2 * i - 1; j++)
System.out.print("*");
System.out.print("\n");
}
What should i fix??
You can check odd numbers in your loop. Please see the following example:
public static void main(String[] args) {
printPattern(5);
}
private static void printPattern(int n) {
int i, j;
for (i = 0; i <= n; i++) {
if (i % 2 != 0) {
for (j = 1; j <= (n - i)/2; j++) {
System.out.print(" ");
}
for (j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
}
for (i = n - 1; i >= 1; i--) {
if (i % 2 != 0) {
for (j = 1; j <= (n - i)/2; j++) {
System.out.print(" ");
}
for (j = 0; j <i; j++) {
System.out.print("*");
}
System.out.println();
}
}
}
Instead of running these two loops from 0 to N twice. Just run half N/2 in each loop.
Example:
public static void main(String[] args) {
int n = 10;
for (int i = 0; i <= (n / 2 + 1); i++) {
for (int j = 1; j <= n - i; j++) System.out.print(" ");
for (int j = 1; j <= 2 * i - 1; j++) System.out.print("*");
System.out.print("\n");
}
// N/2
for (int i = n / 2 - 1; i >= 1; i--) {
for (int j = 1; j <= n - i; j++) System.out.print(" ");
for (int j = 1; j <= 2 * i - 1; j++) System.out.print("*");
System.out.print("\n");
}
}

Print an hourglass pattern

I want to print the pattern in java and I have tried the following code. please guide me to solve my mistake.
import java.util.*;
class sp10
{
public static void main(String args[])
{
int i,j,n;
Scanner sc = new Scanner(System.in);
System.out.println("Enter value of n");
n = sc.nextInt();
for(i=n;i>=1;i--)
{
for(j=i;j<n;j++)
{
System.out.print(" ");
}
for(j=1;j<=(2*i-1);j++)
{
if(j==1 || j==(2*i-1) ||i==n)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println("");
}
for(i=2;i<=n;i++)
{
for(j=i;j<n;j++)
{
System.out.print(" ");
}
for(j=1;j<=(2*i-1);j++)
{
if(j==1 || j==(2*i-1)|| i==n)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println("");
}
}
}
I am trying it in Java. Can you please guide me? It should print 5 stars in the first and the last line. Given below is the exact pattern
*****
* *
* *
*
* *
* *
*****
Well, let's look at the pattern.
n = 5
*****
* *
* *
*
* *
* *
*****
The first line and the last line is just print * n times.
private static void printTop(int n) {
System.out.println("*".repeat(n));
}
private static void printBottom(int n) {
printTop(n);
}
Though I wrote two methods here, you can just define one method like printStar(int n) and reuse it on the first and last line.
The real problem is to implement the middle part. Well, this still can be implemented in a relatively simple way. You just need to move * from column 0 to right and from n-1 to left as the row increased.
private static void printMiddle(int n) {
for (int i = 0; i < n; i++) {
int p = i;
for (int j = 0; j < n; j++) {
if (j == p || j == n - 1 - p) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
p is the offset from column 0 to right or column n-1 to left.
Now, you have everything. You can write the main method like the following:
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter value of n");
int n = sc.nextInt();
printTop(n);
printMiddle(n);
printBottom(n);
}
I suggest the following solution:
import java.util.*;
public class sp10 {
public static void main(String args[]) {
int i, j, n;
Scanner sc = new Scanner(System.in);
System.out.println("Enter value of n");
n = sc.nextInt();
System.out.print(" ");
for (i = 0; i < 2*n - 3; i++) {
System.out.print("*");
}
System.out.println("");
for (i = n-1; i >= 1; i--) {
for (j = i; j <n; j++) {
System.out.print(" ");
}
for (j = 1; j <= (2 * i - 1); j++) {
if (j==1 || j == (2 * i - 1) || i == n ) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println("");
}
for (i = 2; i <= n-1; i++) {
for (j = i; j < n; j++) {
System.out.print(" ");
}
for (j = 1; j <= (2 * i - 1); j++) {
if (j == 1 || j == (2 * i - 1) || i == n) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println("");
}
System.out.print(" ");
for (i = 0; i < 2*n - 3; i++) {
System.out.print("*");
}
}
}
I hope is what you're looking for, because you question was a little bit difficult to understand...
With such solution the output is (for n = 4):
*****
* *
* *
*
* *
* *
*****
Probably, what you intended to do is as follows:
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
int i, j, n;
Scanner sc = new Scanner(System.in);
System.out.print("Enter value of n: ");
n = sc.nextInt();
for (i = n; i >= 1; i--) {
for (j = i; j < n; j++) {
System.out.print(" ");
}
for (j = 1; j <= (2 * i - 1); j++) {
if (j == 1 || j == (2 * i - 1) || (i == n && j % 2 == 1))
System.out.print("*");
else
System.out.print(" ");
}
System.out.println("");
}
for (i = 2; i <= n; i++) {
for (j = i; j < n; j++) {
System.out.print(" ");
}
for (j = 1; j <= (2 * i - 1); j++) {
if (j == 1 || j == (2 * i - 1) || (i == n && j % 2 == 1))
System.out.print("*");
else
System.out.print(" ");
}
System.out.println("");
}
}
}
A sample run:
Enter value of n: 4
* * * *
* *
* *
*
* *
* *
* * * *
However, if you insist that you need to print exactly what you have shown in the question, you can do it as follows:
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
int i, j, n;
Scanner sc = new Scanner(System.in);
System.out.print("Enter value of n: ");
n = sc.nextInt();
for (i = n; i >= 1; i--) {
for (j = i; j < n; j++) {
System.out.print(" ");
}
for (j = 1; j <= (2 * i - 1); j++) {
if ((j == 1 && i != n) || (j == (2 * i - 1) && i != n) || (j != 1 && i == n && j != (2 * i - 1)))
System.out.print("*");
else
System.out.print(" ");
}
System.out.println("");
}
for (i = 2; i <= n; i++) {
for (j = i; j < n; j++) {
System.out.print(" ");
}
for (j = 1; j <= (2 * i - 1); j++) {
if ((j == 1 && i != n) || (j == (2 * i - 1) && i != n) || (j != 1 && i == n && j != (2 * i - 1)))
System.out.print("*");
else
System.out.print(" ");
}
System.out.println("");
}
}
}
Output:
Enter value of n: 4
*****
* *
* *
*
* *
* *
*****

Java ArrayIndexOutOfBoundsException (Minesweeper)

I am trying to make a simple minesweeper that plants n*n/3 mines in a n*n board. The mines are marked by *, and blank spaces are marked by 0. (It does not function as a game yet: I'm trying to make the 'answer sheet' of the minesweeper) And please note that I haven't used any methods on purpose.
I am constantly getting an error at the 23rd line:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 15
I have tried for hours to fix this issue, but none seems to work. Can anyone point out what is wrong and how I should fix my code? Thanks.
import java.util.Scanner;
public class Minesweeper {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
char board[][] = new char [n][n]; // makes board of n*n
int a, b;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
board[i][j] = '0';
}
}
for (int i = 0; i < n * n / 3; i++) { // '*' is a mine
a = (int)(Math.random() * (n - 1) + 1.0);
b = (int)(Math.random() * (n - 1) + 1.0);
board[a][b] = '*';
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
for (int k = i - 1; k <= i + 1 && k >= 0 && k <= n; k++) {
for (int l = j - 1; l <= j + 1 && l >= 0 && l <= n; l++) {
if (board[k][l] == '*' && !(k == i && l == j)) {
board[i][j] = (char)(Character.getNumericValue(board[i][j]) + 1);
}
}
}
}
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
System.out.println(board[i][j]);
}
}
}
}
for (int k = i - 1; k <= i + 1 && k >= 0 && k <= n; k++) {
for (int l = j - 1; l <= j + 1 && l >= 0 && l <= n; l++) {
It should be k < n and l < n. n is already outside the boundaries.
Also
for (int i = 0; i < n * n / 3; i++) { // '*' is a mine
a = (int)(Math.random() * (n - 1) + 1.0);
b = (int)(Math.random() * (n - 1) + 1.0);
board[a][b] = '*';
}
seems wrong, I think it should be
for (int i = 0; i < n * n / 3; i++) { // '*' is a mine
a = (int)(Math.random() * n);
b = (int)(Math.random() * n);
board[a][b] = '*';
}

Empty diamond shape with numbers

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.

Looping Algorithm

How do I make this:
*******
-*****-
--***--
---*---
--***--
-*****-
*******
The following is my code that I have written to try to accomplish the above, but it is not working as expected:
public static void stars(/*int jmlBaris*/) {
for ( int i = 7; i >= 1; i-=2) {
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println("");
}
for (int i = 1; i <= 7; i+=2) {
for (int j = 1; j <= i; j++){
System.out.print("*");
}
System.out.println("");
}
}
public static void main(String[] args) {
stars();
}
}
This is how I might write it.
// three loops
public static void stars(int size) {
for (int y = 0; y < size; y++) {
for (int i = 0; i < y && i < size - y - 1; i++)
System.out.print(' ');
for (int i = Math.min(y, size - y - 1); i < Math.max(y + 1, size - y); i++)
System.out.print('*');
System.out.println();
}
}
or
// two loops
public static void stars(int size) {
for (int y = 0; y < size; y++) {
for (int x = 0; x < size; x++)
System.out.print(
(x >= y && x < size - y) ||
(x >= size - y - 1 && x <= y) ? '*' : ' ');
System.out.println();
}
}
or
// one loop
public static void stars(int size) {
for (int i = 0; i < size * size; i++) {
int y = i / size, x = i % size;
System.out.print(
(x >= y && x < size - y) ||
(x >= size - y - 1 && x <= y) ? '*' : ' ');
if (x == size - 1)
System.out.println();
}
}
Note: Whether this uses one, two or three loops, the time complexity is O(N^2). A simple way to determine this is the number of stars produced is O(N^2) no matter how it is done.
I would do something like this with substrings.
String a = "*******"; //7 stars
String blank = " "; //7 spaces
int j = 7;
for (int i = 0; i < 7; i++) {
if (i > j){
System.out.print(blank.substring(0,i));
System.out.println(a.substring(i,j));
}
else{
System.out.print(blank.substring(0,j));
System.out.println(a.substring(j,i));
}
j--;
}
System.out.println(a);
**Previous edit wouldn't have worked. Changes made.
This works.
Try something like this code I compiled on IDEOne (it seems to work, though):
http://ideone.com/9xZ1YB
class Main
{
public static void main(String[] args)
{
stars();
}
static void stars()
{
final int MAX_WIDTH = 7;
for (int i = 0; i < 7; ++i)
{
int width;
if (i < 3) width = MAX_WIDTH - i * 2;
else if (i > 3) width = (i - 3) * 2 + 1;
else width = 1;
// Before spaces
for (int j = 0; j < (MAX_WIDTH - width) / 2; ++j)
{
System.out.print(" ");
}
// Stars
for (int j = 0; j < width; ++j)
{
System.out.print("*");
}
// After spaces
for (int j = 0; j < (MAX_WIDTH - width) / 2; ++j)
{
System.out.print(" ");
}
System.out.println();
}
}
}
For a beginner in algorithms I would recommend you to break down the structure in sub-parts and then try to solve the pattern.
For this specific pattern it could be broken down into several triangles. Each triangle is then solved by different for loops as shown in the image below.
public static void printPattern(int num) {
// this loop generates first 4 lines
for (int i = 0; i < num / 2 + 1; i++) {
// draws the red triangle of '-'
for (int j = 0; j < i; j++) {
System.out.print("-");
}
// draws the green triangle of '*'
for (int j = i; j < num / 2 + 1; j++) {
System.out.print("*");
}
// draws the blue triangle of '*'
for (int j = i + 1; j < num / 2 + 1; j++) {
System.out.print("*");
}
// draws the orange triangle of '-'
for (int j = 0; j < i; j++) {
System.out.print("-");
}
System.out.println();
}
/* this loop generates last 3 lines */
for (int i = 0; i < num / 2; i++) {
// draws the green triangle of '-'
for (int j = i + 1; j < num / 2; j++) {
System.out.print("-");
}
// draws the red triangle of '*'
for (int j = 0; j < i + 2; j++) {
System.out.print("*");
}
// draws the orange triangle of '*'
for (int j = 0; j < i + 1; j++) {
System.out.print("*");
}
// draws the blue triangle of '-'
for (int j = i + 1; j < num / 2; j++) {
System.out.print("-");
}
System.out.println();
}
}
Using similar technique you could generate any pattern.
If I understood you right, your problem is to print indent in lines 2-7.
Imagine same problem with asterisk symbol replaced by 'x' and whitespace replaced by '-'. Then you need to draw
xxxxxxx
-xxxxx-
--xxx--
---x---
--xxx--
-xxxxx-
xxxxxxx
That means you should output 0, 1, 2 space(s) before asterisks in first, second, thrid strings respectively. I let details for you to figure them out.
public static void stars(/*int jmlBaris*/){
String starstr = "*";
String blank = "_";
int spaceBlank;;
for(int i=7; i>=1;i-=2){
spaceBlank = (7-i)*.5;
String starrep = StringUtils.repeat(starstr, i);
String blankrep = StrinUtils.repeat(blank, spacesBlank);
system.out.println(blankrep + starrep + blankrep);
}
for(int j=3 j<=7; j+=2){
spaceBlank = (7-j)*.5;
starrep = StringUtils.repeat(starstr, j);
String blankrep = StrinUtils.repeat(blank, spacesBlank);
system.out.println(blankrep + starrep + blankrep);
}
}
public static void main(String[] args){
stars();
}
You have little missing to put space on your code. I don't care about right space, who can see that? But left space is very important!!
Try this:
public static void stars(/*int jmlBaris*/) {
for ( int i = 7; i >= 1; i-=2) {
for (int k = 0; k < ((7-i) / 2); k++){ /* Missing Here */
System.out.print(" "); /* Missing Here */
} /* Missing Here */
for (int j = 1; j <= i; j++) {
System.out.print("*");
}
System.out.println("");
}
for (int i = 1; i <= 7; i+=2) {
for (int k = 0; k < ((7-i) / 2); k++){ /* Missing Here */
System.out.print(" "); /* Missing Here */
} /* Missing Here */
for (int j = 1; j <= i; j++){
System.out.print("*");
}
System.out.println("");
}
}
int N = 7;
for (int y=0; y<N; y++)
{
for (int x=0; x<N; x++)
System.out.print( (y-x)*(N-y-x-1)<=0 ? '*' : '-');
System.out.println();
}
or, more symmetrically,
int n = 3;
for (int y=-n; y<=n; y++)
{
for (int x=-n; x<=n; x++)
System.out.print( y*y>=x*x ? '*' : '-');
System.out.println();
}

Categories

Resources