For my assignment I am supposed to make a Draw a diamond with asterisks using methods.
I figured out how to make the first part (centered triangle)
I cannot for the love of God figure it out. I have spent over 4 hours trying different things and I figured how to make an upside down triangle, but the diamond is not working out.
This is what I have for the first part. Can someone tell me how to flip it so that it will form a diamond when used with an upside down version?
{
int rows = userInputHeight;
int starCount = 1;
int spaceCount = rows - 1;
for( int rowCount = 1; rowCount <= rows; rowCount++ )
{
for( int numb = 1; numb <= spaceCount; numb++ )
{
System.out.print(" ");
}
for( int count = 1; count <=starCount; count++ )
{
System.out.print("*");
}
System.out.println();
starCount += 2;
spaceCount--;
}
}
This is what it displays (UserInputHeight = 10):
*
***
*****
*******
*********
***********
This is what I want (UserInputHeight = 19):
*
***
*****
*******
*********
***********
***********
*********
*******
*****
***
*
This is what I have so far for the second part:
{
int rows = userInputHeight;
int starCount = rows*2;
int spaceCount =userInputPadding;
if (userInputHeight % 2 == 0)
{
userInputHeight+=1;
}
for (int rowCount = rows; rowCount >= 1; rowCount --)
{
for (int i = 0; i <= (rows - rowCount)+ spaceCount; i++)
{
System.out.print(' ');
}
for (int i = 1; i < starCount; i++)
{
System.out.print('*');
}
System.out.println();
starCount -=2;
}
}
Please help.
Try this:
public static void drawDiamond(int height) {
if (height % 2 == 0) throw new AssertionError("Height should be an odd number!");
height = (height + 1) / 2;
drawTop(height);
drawBot(height - 1);
}
public static void drawTop(int height) {
int rows = height;
int starCount = 1;
int spaceCount = rows - 1;
for (int rowCount = 1; rowCount <= rows; rowCount++) {
for (int i = 0; i < spaceCount; i++) {
System.out.print(" ");
}
for (int i = 0; i < starCount; i++) {
System.out.print("*");
}
starCount += 2;
spaceCount--;
System.out.println();
}
}
public static void drawBot(int height) {
int rows = height;
int starCount = 2 * (rows - 1) + 1;
int spaceCount = 1;
for (int rowCount = 1; rowCount <= rows; rowCount++) {
for (int i = 0; i < spaceCount; i++) {
System.out.print(" ");
}
for (int i = 0; i < starCount; i++) {
System.out.print("*");
}
starCount -= 2;
spaceCount++;
System.out.println();
}
}
Here is another angle of looking at it.
Note: height strands from the mid-line to the uppermost point.
public static void DrawDiamond(int height)
{
DiamondTop(height);
DiamondBottom(height);
}
public static void DiamondTop(int height)
{
for (int row = 1; row <= height; row++)
{
for (int padding = height - row; padding > 0; padding--)
{
System.out.print(" ");
}
for (int numberOfAsterisks = (row * 2) - 1; numberOfAsterisks > 0; numberOfAsterisks--)
{
System.out.print("*");
}
System.out.println();
}
}
public static void DiamondBottom(int height)
{
for (int row = height - 1; row > 0; row--)
{
for (int padding = row; padding < height; padding++)
{
System.out.print(" ");
}
for (int numberOfAsterisks = (row * 2) - 1; numberOfAsterisks > 0; numberOfAsterisks--)
{
System.out.print("*");
}
System.out.println();
}
}
Related
I am new to java, I want to print a reversed star pattern based on the coordinate. After I set the coordinate, it will then print the star pattern
import java.util.Scanner;
public class coorTest {
public static void main(String[] args) {
int max = 5;
for (int y = 0; y < max; y += 2) {
int left_spacing = (int) Math.floor(y * 1.0 / 2.0);
for (int space = 0; space < left_spacing; space++) {
System.out.print(" ");
}
for (int x = 0; x < (max - y); x++) {
System.out.print("x");
}
System.out.println();
}
}
}
Try this. I am using (0,0) as a first coordinate.
public static void printStar(int x, int y) {
int starCount = 5;
int space = 0;
int count = 0;
// y-axis line move
for(int i=0; i<y; i++) {
System.out.println();
}
for (int i = 0; i < starCount; i++) {
// x-axis space move
for(int xAxis=0; xAxis<x; xAxis++) {
System.out.print(" ");
}
for (int j = 0; j < starCount; j++) {
if (count < space) {
System.out.print(" ");
count++;
continue;
} else if (j >= starCount - count) {
System.out.print(" ");
} else {
System.out.print("*");
}
}
System.out.println();
space++;
count = 0;
}
}
My code is resulting in an infinite loop when i run it. Don't know whats wrong.
!(https://d2vlcm61l7u1fs.cloudfront.net/media%2F1aa%2F1aa1af9f-41ff-48d8-89e9-7b093a909045%2Fphpbrt5Fy.png)
I have tried the code below. It compiles properly.
public class Project3_1 {
//declare SEGMENTS and HEIGHT
public static final int SEGMENTS = 4;
public static final int HEIGHT = 4;
public static final int TOTAL = (2*(SEGMENTS)) + (2*(HEIGHT)) - 3;
public static void TopTree(int SEGMENTS, int HEIGHT) {
for (int s = 1; s <= SEGMENTS; s++) {
for (int h = 1; h <= HEIGHT; h++) {
int ASTERISKS = ((2*s) + (2*h) - 3);
int SPACES = ((TOTAL - ASTERISKS)/2);
//spaces
for (int b = 1; b <= SPACES; b++) {
System.out.print(" ");
}
//Asterisks
for (int a = 1; a <= ASTERISKS; a++) {
System.out.print("*");
}
System.out.println();
}
}
}
public static void TreeBase() {
int x = (TOTAL - 7)/2;
for (int i = 1; i <= (TOTAL-1)/2; i++){
System.out.print(" ");
}
System.out.println("*");
for (int i = 1; i <= (TOTAL-1)/2; i++){
System.out.print(" ");
}
System.out.println("*");
for (int i = 1; i <= x; x++){
System.out.print(" ");
}
for (int i = 1; i <= 7; i++) {
System.out.print("*");
}
for (int i = 1; i <= (TOTAL - (x + 7)); i++) {
System.out.print(" ");
}
System.out.println("");
}
public static void main (String[] args){
TopTree(SEGMENTS, HEIGHT);
TreeBase();
}
}
Check your third for loop in TreeBase(), you increment the wrong variable. The code you posted runs fine for me, it just doesn't make that bottom line of asterisks due to that loop I mentioned not being correct. Once you fix that, you should be good
I need help making a mirrored triangle like this:
* *
** **
*** ***
********
I can get each one seperatly, but I can't combine them.
public static void main(String[] args){
for( int i = 1; i <= 5; i++ ){
for( int j = 0; j < i; j++ ){
System.out.print("*");
}
System.out.println();
}
for(int i = 0; i < 6; i++)
{
for(int j = 5; j > 0; j--)
{
if(i < j)
System.out.print(" ");
else
System.out.print("*");
}
System.out.println();
}
}
You need to track the position from both sides to be able to show * at correct location. Here is the solution:
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 10; j++) {
if (j <= i || j > 10 - i) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
You can do it using this code.
public class Test {
public void sizeOfTri(int triSize) { //Number of lines
int line = 1;
for(int i = 0; i < triSize; i++) { //Handles Each line
int temp = triSize * 2;
for(int j = 1; j < temp; j++) { //Handles Each space on the line
if(j <= line && j == triSize || j >= temp - line && j == triSize) { //For the very last line because it needs an extra *
System.out.print("**");
} else if(j <= line || j >= temp - line) { //For normal lines
System.out.print("*");
} else if(j == triSize) {
System.out.print(" "); //For the second to last line because it needs an extra space to make it look mirrored
} else { //For normal lines
System.out.print(" ");
}
}
System.out.println();
line++;
}
}
public static void main(String[] args) {
new Test().sizeOfTri(4);
}
}
I commented on next to if statements on which part does what. This will produce an output which looks like the below when run
* *
** **
*** ***
********
Although, all the above implementations are really good ones. I thought of doing it bit differently and make use of 2-D arrays.
package algorithms;
public class DrawMirror {
static void initialize(String[][] array){
for (int i=0; i<MAX_X; i++){
for (int j=0; j < MAX_Y; j++){
array[i][j] = " ";
}
}
}
static void draw(String[][] array, int x, int y){
for (int i=0; i < y; i++){
array[x][i] = "*";
array[x][MAX_Y-i-1] = "*";
}
}
final static int MAX_X = 4;
final static int MAX_Y = 8;
public static void main(String[] args) {
String[][] array = new String[MAX_X][MAX_Y];
initialize(array);
for (int i=0; i < MAX_X ; i++){
draw(array,i,i+1);
}
for( int i = 0; i < MAX_X; i++ ){
for( int j = 0; j < MAX_Y; j++ ){
System.out.print(array[i][j]);
}
System.out.println();
}
}
}
The following code is a function with variable height.
public static void printDoubleTriangle(int height) {
for(int i = 0; i < height; i++) {
for(int j = 0; j < 2*height; j++) {
if(j <= i || (2*height - j - 1) <= i) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
My code needs to multiply each row of an array by each column of the next. The user inputs the height and width and the program will randomly generate the array values. It doesn't give any errors if the arrays are equal for example (3x3)(3x3) or even if you do (3x2)(2x3). if however you enter something like (3x3)(3x2) it gives an out of bounds exception.
public class Multiply {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int width = -1;
int height = 0;
int width2 = 0;
int height2 = 0;
while (width != height2) {
while (height <= 0) {
System.out.print("Enter a height for array1: ");
height = checkInt(scan);
}
while (width <= 0) {
System.out.print("Enter a width for array1: ");
width = checkInt(scan);
}
while (height2 <= 0) {
System.out.print("Enter a height for array2: ");
height2 = checkInt(scan);
}
while (width2 <= 0) {
System.out.print("Enter a width for array2: ");
width2 = checkInt(scan);
}
if (width != height2) {
System.out
.println("Error! Dimensions of matrices not compatible. Try again.");
width = -1;
height = 0;
width2 = 0;
height2 = 0;
}
}
int array1[][] = randomMatrix(height, width);
int array2[][] = randomMatrix(height2, width2);
int product[][] = matrixMultiply(array1, array2, height, width2);
printArray(product);
}// end of main method
public static int[][] randomMatrix(int height, int width) {
int array1[][] = new int[height][width];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
array1[i][j] = (int) (-10 + Math.random() * 20);
}
}
return array1;
}// end of randomMatrix method
public static int[][] matrixMultiply(int[][] array1, int[][] array2, int height, int width) {
int[][] product = new int[height][width];
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array1[i].length; j++) {
int prod = 0;
for (int k = 0; k < array2.length; k++) {
prod = prod + array1[i][k] * array2[k][j];
}
product[i][j] = prod;
}
}
return product;
}// end of matrixMultiply method
public static void printArray(int[][] array) {
System.out.println(" ");
System.out.println("Row Major Representation:");
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
System.out.println(" ");
System.out.println("Column Major Representation:");
for (int i = 0; i < array[1].length; i++) {
for (int j = 0; j < array.length; j++) {
System.out.print(array[j][i] + " ");
}
System.out.println();
}
}
public static int checkInt(Scanner scan) {
int width = 0;
if (scan.hasNextInt()) {
width = scan.nextInt();
return width;
} else {
scan.next();
return 0;
}
}
}// end of public class Multiply
The value of the variable "j" (Line 82) in its final iteration is causing the Out of Bounds Exception. The error occurs for (3x3)(3x2) because in the final "j" iteration, j equals 2, making the value higher than 1 (the highest index value for j's location). Adding some logic to check for when j > the highest index will prevent the issue.
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();
}