Looping Algorithm - java

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();
}

Related

Print star pattern based on coordinate

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;
}
}

String,which repeats ,but not starts from the beginning in Java (diamond pattern

This is the work that i done so far:I have to print diamond pattern which always starts with uppercase from string, which repeats,but not always starts from the beginning.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String userInput = keyboard.next();
userInput = Character.toUpperCase(userInput.charAt(0)) + userInput.substring(1);
int i;
int j;
if (userInput.length() % 2 != 0) {
for(i = 1; i < userInput.length(); i += 2) {
for(j = 0; j < userInput.length() - 1 - i / 2; ++j) {
System.out.print(" ");
}
for(j = 0; j < i; ++j) {
System.out.print(userInput.charAt(j));
}
System.out.println("");
}
for(i = userInput.length(); i > 0; i -= 2) {
for(j = 0; j < userInput.length() - 1 - i / 2; ++j) {
System.out.print(" ");
}
for(j = 0; j < i; ++j) {
System.out.print(userInput.charAt(j));
}
System.out.print("\n");
}
} else {
for(i = 2; i < userInput.length(); i += 2) {
for(j = 0; j < userInput.length() - 1 - i / 2; ++j) {
System.out.print(" ");
}
for(j = 0; j < i; ++j) {
System.out.print(userInput.charAt(j));
}
System.out.println("");
}
for(i = userInput.length(); i > 0; i -= 2) {
for(j = 0; j < userInput.length() - 1 - i / 2; ++j) {
System.out.print(" ");
}
for(j = 0; j < i; ++j) {
System.out.print(userInput.charAt(j));
}
System.out.print("\n");
}
}
}
For example my input is "Peter".
So my output is:
P
Pet
Peter
Pet
P
but it must be:
P
Ete
Rpete
Rpe
T
I dont know what to change to make this work
Here's a shorter version of your code:
public static void main(String[] args) {
String userInput = "Peter";
int length = userInput.length();
int m, j, i, n = 0;
for (m = length % 2 > 0 ? 1 : 2; m < length * 2; m += 2) {
i = m < length ? m : length * 2 - m;
for (j = 0; j < length - 1 - i / 2; ++j) {
System.out.print(" ");
}
for(j = 0; j < i; ++j) {
char c = userInput.charAt(n++ % length);
c = j == 0 ? Character.toUpperCase(c) : Character.toLowerCase(c);
System.out.print(c);
}
System.out.println("");
}
}
You need some few changes:
Declare int n=0; after int j;
Always print userInput.charAt(n++ % userInput.length()) instead of charAt(j)
In order to get only the first character in line in uppercase:
char c = userInput.charAt(n++ % userInput.length());
c = j == 0 ? Character.toUpperCase(c) : Character.toLowerCase(c);
System.out.print(c);
Check the modulo operator.
With these changes, you'll get this output:
P
Ete
Rpete
Rpe
T
Given the fact that the input itself gets printed in a cylic manner, we can make use out of it. My proposal would be to concatenate the input string and print out the substrings which are determined by the structure of the diamond pattern.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String userInput = keyboard.next();
String concatenated = userInput;
// build up the index array
int i, cumSum = 0;
ArrayList<Integer> helperIndex = new ArrayList<>();
for(i = 1; i < userInput.length(); i += 2) {
helperIndex.add(i);
cumSum += i;
}
for(i = userInput.length(); i > 0; i -= 2) {
helperIndex.add(i);
cumSum += i;
}
int numOfWordRepitition = cumSum / userInput.length() ;
for (i = 0; i < numOfWordRepitition; i++){
concatenated += userInput;
}
// print out diamond
String substr;
int prev = helperIndex.get(0);
int next = helperIndex.get(0);
substr = concatenated.substring(0 , helperIndex.get(0));
System.out.println(Character.toUpperCase(substr.charAt(0)) + substr.substring(1));
for(i = 1; i < userInput.length(); i++){
next += helperIndex.get(i);
substr = concatenated.substring(prev , next);
substr = Character.toUpperCase(substr.charAt(0)) + substr.substring(1);
System.out.println(substr);
prev = next;
}
}

Printing diamonds from *'s

I am trying to System.out.print() a diamond out of *'s. So far I have spent a good 5 hours on trying to figure out how to reverse print the bottom triangle of the diamond.
I can worry about the spacing to complete the diamond later. (I have it worked for the most part).
If someone could explain to me what I am doing wrong and how the right way works I would greatly appreciate it.
private static void diamond()
{
int numLines = 0;
System.out.println("How many lines would you like in the Diamond?");
numLines = scan.nextInt();
if (numLines / 2 == 0) //if number is even, make odd.
{
numLines++;
}
for(int i = 0; i <= numLines ; i++) // Controls #Lines
{
if(i <= numLines / 2)
{
for(int j = 0; j < i * 2 - 1; j++) // Controls #Stars small upright triangle
{
System.out.print("*");
}
}
else
{
for(int k = numLines; k > i / 2; k--) // Controls # of spaces
{
System.out.print("*");
}
/*for(int j = numLines/2 - i, l = i; l > j; j++) // Controls #Stars small upright triangle
{
String stars = "*";
System.out.print(stars);
}*/
}
System.out.println("");
}
}
`
What happens to your attempt is that you loop through the half (of the lines) of your diamond [the number of lines in second/first half] times.
You'd want to do a if-statement each loop, not an if and a for in each loop
Probably you want this
Just adjust it for user input values
public static void main(String[] args) {
System.out.print("Reverse diamond: \n");
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("*");
System.out.print("\n");
}
System.out.print("\n\nDiamond from starts: \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("*");
System.out.print("\n");
}
}
output:

Creating a double mirrored triangle

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();
}
}

Height of Java Diamond Asterisk

How can i get this code to display the height correctly? So if the width of the diamond asterisk is 3, and the height is 5, then the diamond will look like this.
*
***
***
***
*
It just adds any excess height to the middle. Here is my code so far. It can do the width just fine.
public static void main(String[] args) {
int width, height, heightT;
Scanner scan = new Scanner(System.in);
while(true) {
System.out.println("Enter width of diamond (odd number between 0-19): ");
width = scan.nextInt();
if (width % 2 != 0) {
if (0 <= width && width <= 19) {
break;
}
}
}
while(true) {
System.out.println("Enter height of diamond (greater than or equal to width): ");
height = scan.nextInt();
if(height >= width) {
heightT = height - width;
break;
}
}
for(int i = 1; i < width + 1; i += 2) {
for(int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for(int j = 0; j < i; j++)
System.out.print("*");
System.out.print("\n");
}
for(int i = width - 2; 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("*");
System.out.print("\n");
}
}
When solving this type of logic you have to always look at the things that you know never change. In this case, 3 things never change:
1. The first line. Always equal to one asterisk.
2. The middle line. Always equal to width in asterisks.
3. The last line. Always equal to one asterisk.
Now, split the diamond in two by the middle row. Notice the total height will always be the height of the top part (or bottom) times 2 plus 1 (the middle row). You get something more less like this:
for(int i = 0; ((i*2)+1) <= height; i++){
//Print top
}
// Print middle row outside of loops or inside if you must.
for(int i = 0; ((i*2)+1) <= height; i++){
//Print bottom.
}
EDIT: This would only be true for diamonds where height is greater than or equal to the width.
EDIT: This code solves your problem (given height is greater than or equal to width). However, it does not handle width = 0 or width = 1 properly. I trust that would be trivial enough for you to do.
public static void main(String[] args) {
int height = 9, width = 9;
int spaces = (width - 1) / 2, asterisks = 1;
for(int i = 0;((i*2)) < height; i++){
for(int ii = 0;ii < spaces;ii++){
System.out.print(" ");
}
for(int ii = 0;ii < asterisks;ii++){
System.out.print("*");
}
spaces--;
if(asterisks < width)asterisks += 2;
System.out.println();
}
spaces = 0;
for(int i = 0; ((i*2)+1) < height; i++){
if(width < height){
for(int ii = 0;ii < spaces;ii++){
System.out.print(" ");
}
for(int ii = 0;ii < asterisks;ii++){
System.out.print("*");
}
}else{
for(int ii = 0;ii < (spaces + 1);ii++){
System.out.print(" ");
}
for(int ii = 0;ii < (asterisks - 2);ii++){
System.out.print("*");
}
}
spaces++;
asterisks -= 2;
System.out.println();
}
}
You can calculate the difference between height and width and reuse your logic in a while loop.
for(int i = 1; i < width + 1; i += 2) {
for(int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for(int j = 0; j < i; j++)
System.out.print("*");
System.out.print("\n");
}
int dif = height-width;
while(dif !=0){
for(int i = width; i < width + 1; i += 2) {
for(int j = 0; j < 9 - i / 2; j++)
System.out.print(" ");
for(int j = 0; j < i; j++)
System.out.print("*");
System.out.print("\n");
}
dif--;
}
for(int i = width - 2; 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("*");
System.out.print("\n");
}

Categories

Resources