Printing a centered pyramid in Java with ascending and descending numbers - java

I'm trying to print a centered pyramid of 2^n, where 2^row# is the centered number of each row, the numbers to the left are ascending to 2^row# and the numbers to the right are descending. I'm pretty new to Java and it took me a really long time to get this much. But now I'm stuck. The last row is the only row that is correct. I don't know how to make it so 64 is not printed on every line. Can anyone please give me a hint?
I've tried messing with every single parameter - starting the last loop with the first row, the last row, changing the starting power, etc. and I just can't figure it out.
Thank you for any hints!
public static void main (String [] args){
int row;
for (row = 0; row <= 8; row++){ // Prints each row
for (int spaces = 8; spaces >= row; spaces --){ // Prints out spaces to left
System.out.print(" ");
}
int power1 = 0; // Power that 2 is being raised to
for (int i = 0; i < row; i++) { // Prints left side of the pyramid
System.out.print(" " + (int)Math.pow(2, power1));
power1++;
}
int power2 = 7;
for (int i = 1; i < row; i++) { // Prints right side of the pyramid
power2--;
System.out.print(" " + (int)Math.pow(2, power2));
}
System.out.println();
}
}
}

Your problem lies in the fact you always start the right side of the pyramid at 2^7, since you hard code the power2 = 7 decleration and assignment. If you start this value instead at the current row - 1, you get the behavior you're looking for. Code:
public static void main (String [] args){
int row;
for (row = 0; row <= 8; row++){ // Prints each row
for (int spaces = 8; spaces >= row; spaces --){ // Prints out spaces to left
System.out.print(" ");
}
int power1 = 0; // Power that 2 is being raised to
for (int i = 0; i < row; i++) { // Prints left side of the pyramid
System.out.print(" " + (int)Math.pow(2, power1));
power1++;
}
int power2 = row - 1;
for (int i = 1; i < row; i++) { // Prints right side of the pyramid
power2--;
System.out.print(" " + (int)Math.pow(2, power2));
}
System.out.println();
}

This part is not right.
int power2 = 7;
for (int i = 1; i < row; i++) { // Prints right side of the pyramid
power2--;
System.out.print(" " + (int)Math.pow(2, power2));
}
On row 2 you get power2=6 so you display 2^6=64.
You should instead be doing something like
int power2 = power1;
for (int i = 1; i < row; i++) { // Prints right side of the pyramid
power2--;
System.out.print(" " + (int)Math.pow(2, power2));
}

You are assigning constant to power2 instead of depending value on row. Can you try this please.
int power2 = row-1;

Related

How to zigzag numbers in floyd's triangle pattern?

I have found a way for zigzag matrix but I am willing to find same as clean code for triangle pattern.
Example:
input = 3
Output:
1
32
456
I already coded a numbered matrix code here:
int k=0;
int t=1;
int n=4;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
k+=t;
System.out.print(k);
}
k=k+n+t;
t=-t;
System.out.println();
}
Output:
1234
8765
9101112
16151413
int n = 6;
int num = 0;
int step = 1;
for (int i = 1; i <= n; i++) {
// num : (i² - i + 2)/2 .. same + i - 1
for (int j = 0; j < i; j++) {
num += step;
System.out.print(num);
System.out.print(' ');
}
num += i + (1 + 3*step)/2;
step = -step; // zig resp. zag
System.out.println();
}
Helpful was numbering i as row with exactly i elements.
Yielding
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15
21 20 19 18 17 16
The problem was that every row i of i numbers has a lowest value (i² - i + 2)/2,
and for the next zigzagging number one needs to consider the following step.
From the last row number to the first row number of the next line has two cases:
step -1
step 1
Both formulas of both cases can be unified by the step.
step i num
+ 1 1 -> 4 += i + 2
- 2 2 -> 3 += i - 1
+ 3 6 -> 11 += i + 2
- 4 7 -> 10 += i - 1
The following will work:
public static void zigZag(int rows) {
int current = 1;
int increment = 1;
for (int row = 1; row <= rows; row++) {
int width = row + current;
for (int element = current; element < width; element++) {
System.out.print(current);
current+=increment;
}
System.out.println();
current += row + 0.5 - (0.5*increment);
increment = -increment;
}
}
Edit: just a note because I suspect your question might be homework motivated, so it might help if you can understand what's going on instead of just copy-pasting.
All that really needed to change was to use the external loop variable (the one that was originally creating your matrix square, which I've called row) in the inner loop which prints the individual elements of the row.
This is then used to calculate the first element of the next row. The increment value does the same as it does in your original, but now it can also be used to have the zig-zag pattern go up in integers other than 1.
Starting from the top of the triangle (1) will be row 1, all subsequent even rows are printed in reverse. Knowing that you can try something like this:
public class StackOverflow {
public static void main(String[] args) {
int triangleSize = 5;
int counter = 1;
int rowSize = 1;
for (int i = 1; i <= triangleSize; i++) {
if (i % 2 == 0) {
// Reverse number sequence
int reverseCounter = counter + rowSize - 1;
for (int j = 0; j < rowSize; j++) {
System.out.print(reverseCounter--);
counter++;
}
} else {
for (int j = 0; j < rowSize; j++) {
System.out.print(counter++);
}
}
System.out.println("");
rowSize++;
}
}
}
Keep track what row you're on (rowSize) and what value you're on (counter). When you're on an even row you have to start with the highest value that row will have and count backwards from it, but still increment your normal counter (int reverseCounter = counter + rowSize + 1).
Result:
1
32
456
10987
1112131415
Try this I coded it for you:
public class TriangleNum{
public static void main(String[] args) {
getTringle(5);
}
public static void getTringle(int j){
for (int i =0; i<j;i++) {
System.out.print(i+ "\r" );
for (int k =0; k<i;k++) {
System.out.print(k+ "\t" );
}
}
}
}
//Using C Language
#include<stdio.h>
int main(){
int n,count=1,k=1;
printf("Enter number of lines:\n");
scanf("%d",&n);
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
if(i%2==1){printf("%d",count);count++;}
else{printf("%d",count);count--;}}
count=count+k;
if(i%2==1){k=k+2;}
printf("\n");
}
return 0;
}

java nested loop logic for triangle's left side

Okay I am so tired of struggling with this and right off the bat I feel really stupid so please be gentle.. I've searched the stack overflow and web and still not finding anything. I am using a nested loop to create a triangle that looks like this:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
...etc. through 128 in the center column.
My loop for the left side renders to the right of my triangle instead of to the left. I'm pretty sure that after I receive an answer I will be hitting my head w/the palm of my hand and saying duh repeatedly. Anyway thanks for your help. I especially want an explanation of the logic. Here is the code.
public class Pyramid_center_x2_0519 {
public static void main(String[] args) {
for (int centerColumn = 1; centerColumn <= 128; centerColumn *=2){
for (int j = 8; j > 1; j--) {
System.out.printf("%7s", "");
}
for (int rightSide = centerColumn; rightSide > 0; rightSide/=2){
System.out.printf("%7d", rightSide);
}
for (int leftSide = 2; leftSide < centerColumn; leftSide*=2){
System.out.print( leftSide );
}
System.out.println("");
}
}
}
Here is the way it renders:
Thanks again.......
UPDATED CODE 12 P.M. 5-31-16: I understand Java prints left to right. Below I have placed the left hand loop before the right side loop but my spacing in front of the triangle is not behaving. Thank you all... again
for (int centerColumn = 1; centerColumn <= 128; centerColumn *=2){
for (int j = 8; j > 0; j--) {
System.out.printf("%7s", "");
}
for (int leftSide = 1; leftSide < centerColumn; leftSide*=2){
System.out.print( leftSide );
}
for (int rightSide = centerColumn; rightSide > 0; rightSide/=2){
System.out.printf("%7d", rightSide);
}
System.out.println("");
}
}
}
There is no way you can print left side after right and center side.
Java prints from left to the right.
(unless you use some arabic encoding)
Well, you already solved most of your Problems and your last updated version already prints the numbers correctly.
The only thing you still need to fix is the formatting to make it look nice.
Starting from your current code there are 2 things that need changing:
All your printed numbers are supposed to take up the same space (7). You already formatted your "right side" printed numbers in that way, all you have to do is do the same for the other numbers.
You currently allways add 8*7 spaces in front of the line, which of course isn't correct. If you look at the pyramid you can clearly see that 8*7 spaces is correct for the first line, but the second line would need 7*7 spaces in front, the third 6*7 etc. pp.
That means to get the correct formatting for you pyramid you have to modify your loop that prints the spaces to run 1 less time with each iteration of your main loop.
Here is one way how you could update your code to add those 2 changes (I added comments in front of the lines i changed as explanation):
public static void main (String[] args) throws java.lang.Exception
{
/** I added this counter to keep track
* of what iteration/line the loop currently is (see 2.)
*/
int iteration = 0;
for (int centerColumn = 1; centerColumn <= 128; centerColumn *=2){
/** Here we changed the loop condition
* from "j > 0" to "j > iteration"
* (So as iteration gets bigger, the loop runs less often)
*/
for (int j = 8; j > iteration; j--) {
System.out.printf("%7s", "");
}
for (int leftSide = 1; leftSide < centerColumn; leftSide*=2){
/** This should be self explanatory.
* You already did the same for rightSide.
* This will take care of 1.
*/
System.out.printf("%7d", leftSide );
}
for (int rightSide = centerColumn; rightSide > 0; rightSide/=2){
System.out.printf("%7d", rightSide);
}
/** Here we increment our counter with each iteration aka line that is printed */
iteration++;
System.out.println("");
}
}
Try this
Edited: First try to put your spaces before putting your number in triangle(here my first inner for loop is doing) then apply some logic to print the number at its position accordingly.
static DecimalFormat df = new DecimalFormat("#");
public static void main(String[] args) {
for (int i = 1; i < 10; i += 2) {
for (int k = 0; k < (4 - i / 2); k++) { // first
System.out.print(" ");
}
for (int j = 0; j < i; j++) { // second
if (Math.pow(2, j) <= i)
System.out.print(df.format(Math.pow(2, j)));
else
System.out.print(df.format(Math.pow(2, i - j - 1)));
}
System.out.println("");
}
}
I think your approach is not good. Try this algorithm:
public class Main {
public static void main(String[] args) {
int levels = 8;
int lastLevelWidth = levels*2 + 1;
for (int i=0; i<levels; i++) {
int blankPositions = (lastLevelWidth - 1)/2 - i;
for (int j=0; j<blankPositions; j++)
print(" ");
int levelWidth = i*2 + 1;
int numberPositionsPerSide = (levelWidth-1)/2;
for (int j=0; j<numberPositionsPerSide; j++) {
print(Math.pow(2, j));
}
print(Math.pow(2, i));
for (int j=numberPositionsPerSide-1; j>=0; j--) {
print(Math.pow(2, j));
}
System.out.println();
}
}
public static void print(String string) {
System.out.print(string);
int spaces = 5 - string.length();
for (int i=0; i<spaces; i++)
System.out.print(" ");
}
public static void print(double n) {
print(Integer.toString((int)n));
}
}

Pyramids using asterisks

One of my questions was a problem asked by my prof and that is write a loop that will display the following patterns
I have figured out A but my problem is B the second one
My code for A
for( row = 10; row >= 0; row--) // number of rows
{
for( cnt = 0; cnt < row; cnt++) // number of stars
{
System.out.print( "*");
}
System.out.println();
}
I have done multiple different ways and have came to the conclusion that A)
is going
row(10)1.2.3.4.5.6.7.8.9.10
row(9) 1.2.3.4.5.6.7.8.9
row(8) 1.2.3.4.5.6.7.8
and B) is doing something in the lines of
row(10) 1.2.3.4.5.6.7.8.9.10
row(9) 2.3.4.5.6.7.8.9.10
row(8) 3.4.5.6.7.8.9.10
Can anyone help me with what I am missing in my code to turn it into the mirror image.
The easy way to handle such a problem is to know how many lines you have and base your code on that. The first for loop represents how many lines the pyramid has, in this case, 10. The way to base the number of stars or spaces on the line is the following.
Basically the formula is:
Rate of change*(line) + X = Amount of stars/spaces at that line
Start by getting rate of change, then you get the X and implement it in your code.
In the first line you have 10 stars, then on the second 9 stars, on the third 8 stars, so on and so forth. In order to get rate of change, you subtract the second amount of stars with the first, or the third with the second (you get the same result, since it is decreasing at the same rate). Try 9-10 or 8-9 you get -1. So if you pick the first line, by using the formula you get -1*1 + X = 10, where X will be equal 11. If you would check the "-1*line +11" inside the second for loop, and take line = 1, the answer you get will be 10, which is the amount of stars you have on line 1. You will get the same formula if you take line 2 or 3. Take line 3, you get -1*3 + X = 8 which results in X = 11.
Note that what you use in your code is left hand side of the formula i.e Rate of change*(line) + X
Next you have the number of spaces. I do not know how many spaces you have on the first line, therefore I assumed you have 10 spaces, and incremented by 3. So 10 on the first line, 13 on the second and so on. Again you do the same steps. You need to base your calculations on the amount of lines, first by getting the rate of change by subtracting the amount of spaces on the second line by the first (13- 10). Take line 1. 3*1 + X = 10 (since on the first line we have 10 spaces). X = 7. Try line number 2, 3*2 + X = 13, you still get X = 7. Now you know you have a solid constant formula you can use in your code.
We implement it in the code.
public class Pyramid {
public static void main (String [] args){
for(int line = 1; line <=10; line++){
//j is decreasing since number of stars are decreasing
for(int j = -1*line + 11; j >=1; j--){
System.out.print("*");
}
//k is decreasing since number of spaces are increasing
for(int k = line; k <= 3*line +7; k++ ){
System.out.print(" ");
}
for(int j = -1*line + 11; j >=1; j--){
System.out.print("*");
}
//End of line, start new one
System.out.println();
}
}
look into String.format() where you can pad (left or right) any string to a certain width like so:
String stars = //use your loop from (a) to produce a number of stars
String toOutput = String.format("%10s", stars);
You want to try something like this:
for( int row = 10; row >= 0; row--) // number of rows
{
for( int cnt = 10; cnt - row >= 0; cnt--) // number of stars
System.out.print(" ");
for (int cnt = 0; cnt <= row; cnt++)
System.out.print( "*");
System.out.println();
}
Hope that helps.
There you go ! I put everything into a class for you so that you can run the program directly..
I am not implementing it very efficiently probably.
As you can see I am printing spaces which start from 10, and for every line I add 2 more spaces in order to mirror the "asterisk" effect
public class asterisk {
public static void main(String[] args) {
int spaces=10;
for( int row = 10; row >= 0; row--) // number of rows
{
for( int cnt = 0; cnt < row; cnt++) // number of stars
{
System.out.print( "*");
}
for( int cnt = 0; cnt < spaces; cnt++) {
System.out.print( " "); }
spaces=spaces+2;
for( int cnt = 0; cnt < row; cnt++) {
System.out.print( "*"); }
System.out.println();
}
}
}
If you want more or less than 10 spaces between A and B you just change the initial value that you set the variable "spaces" to !
Here is a complete code -
int main(){
char star = '*';
char space = ' ';
int noOfTimesToPrint = 10;
int noOfSpaceToPrint = 1;
int line = 0;
int starCount = 0;
int spaceCount = 1;
for(line=1; line<=10; line++){
for(starCount=1; starCount<=noOfTimesToPrint; starCount++){
printf("%c", star);
}
for(spaceCount=1; spaceCount<=noOfSpaceToPrint; spaceCount++){
printf("%c", space);
}
noOfSpaceToPrint = noOfSpaceToPrint+2 ;
for(starCount=1; starCount<=noOfTimesToPrint; starCount++){
printf("%c", star);
}
printf("\n");
--noOfTimesToPrint;
}
}
Some explanations -
You can adjust the initial no of space to print by setting noOfSpaceToPrint. Here it is set for printing 1 space. You can adjust according to your requirement.
The first inner for loop block print the A portion of your image
The second inner for loop block print the space portion of your image and
The last inner for loop portion print the B portion of your image
The outer for loop portion is used to print a line that is -
line 1 : ********** **********
and so on
Hope It will help.
Thanks a lot
Output of the code is :
Probably shouldn't word your question as asking for homework answers but nonetheless:
public class PyramidPrinter
public static void printPyramid(boolean mirrorize) {
for (int i = 10; i > 0; i--) {
if (mirrorize) {
for (int j = 10; j > 0; j--) {
if (j <= i) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
} else {
for (int j = 0; j < 10; j++) {
if (i > j) {
System.out.print("*");
} else {
System.out.print(" "); // might not even need
}
}
}
System.out.println();
}
}
public static void main(String[] args) {
printPyramid(false); // A
printPyramid(true); // B
}
}
The key here is use of a combination of forward and backward incrementing for-loops, to essentially pad spaces with asterisks and pad asterisks with spaces.
Results:
**********
*********
********
*******
******
*****
****
***
**
*
**********
*********
********
*******
******
*****
****
***
**
*
This is my ending result for my code based on all the information I have gathered here, thank you all. `
for( row = 10; row >= 0; row--) // number of rows
{
for( cnt= 10; cnt - row >= 0; cnt--) // number of spaces before the asterisk
{
System.out.print( " ");
}
for( cnt = 0; cnt < row; cnt++) // number of stars
{
System.out.print("*");
}
System.out.println();
}
}
`
public class Printstar {
public static void main(String[] args){
int space=1;
for(int i=1;i<=10;i++)
{
for(int j=0;j<10-i;j++)
{
System.out.print("*");
}
for(int j=0;j<space;j++)
System.out.print(" ");
for(int j=0;j<10-i;j++)
System.out.print("*");
System.out.println();
space=space+2;
}
}}

Patterns using for loops

I am supposed to create this pattern based on the number a user enters. The number the user enters corresponds to the number of rows and stars in each row.
*
**
***
****
*****
I was told to only use nested for loops and cannot use printf(). This is only part of the code that I am working on.
for (int row = 1; row <= size; row++) {
for (int column = 1; column <row; column++) {
System.out.print(" ");
}
for (int column = 1; column <= row; column++) {
System.out.print("*");
}
System.out.println();
}
I cannot seem to make my output as shown above. Instead I get this:
*
**
***
****
*****
Could someone give me a hint as to what I am supposed to do? I have spent 2 hours but still can't figure it out.
For each row, you should output maximum size characters; so if size = 5, on third row, if output three stars, then you need size-row spaces => 5 - 3 = 2.
In code:
for (int row = 1; row <= size; row++) {
for (int column = 1; column <= size-row; column++) {
System.out.print(" ");
}
for (int column = 1; column <= row; column++) {
System.out.print("*");
}
System.out.println();
}
Sample: http://ideone.com/hC5HDQ
You want to start with more spaces, then remove them until there is not more left. But while removing spaces, you also want to add and additional " * ". So for every space removed you will add an " * "
Try this
int i=5;
do{
int j=5;
while(j>i){
System.out.print("*");
j--;
}
System.out.println();
i--;
}while(i>0);

how to print the row numbers in a 2d array game board in java

I am working on a java Othello game and am using a 2D array with padding to build the board. I have the board printing just fine, the columns are labeled "a -h" but i need the rows to be numberd "1-8" and cannot figure out how to do this. my code is as follows:
void printBoard() {
String results = "";
OthelloOut.printComment(" a b c d e f g h");
int row = board.board.length;
int col = board.board[0].length;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
results += " " + pieces[board.board[i][j] + 2];
}
OthelloOut.printComment(results);
results = "";
}
}
the othelloOut class sort of extends the System.out print statements
public class OthelloOut {
static public void printMove(PieceColor color, Move amove){
System.out.printf("%s %s\n", color, amove);
}//printMove
static public void printComment(String str){
System.out.printf("C %s\n", str);
}//printComment
static public void printReady(PieceColor color){
System.out.printf("R %s\n", color);
}//printReady
}//OthelloOut
any help will be much appreciated. If this needs to be clarified more just let me know! thanks.
UPDATE: Numbers print but i prints 0 - 9 and i want it to skip the digits 0 and 9 to where its blank in the positions of those two numbers. Any suggestions? Thanks for the help guys!
Your best bet is doing it here:
for (int i = 0; i < row; i++) {
OthelloOut.printComment(i); // Obviously not exactly like this.
for (int j = 0; j < col; j++) {
results += " " + pieces[board.board[i][j] + 2];
}
OthelloOut.printComment(results);
results = "";
}
Remember that you're not using println, you're using print. You want all other text to be printed onto the same line as i.
And while I'm here..
I would be using a StringBuilder, instead of concatenating a String.
for (int i = 0; i < row; i++) {
StringBuilder results = new StringBuilder();
OthelloOut.printComment(i); // Obviously not exactly like this.
for (int j = 0; j < col; j++) {
results.append(pieces[board.board[i][j] + 2]);
}
OthelloOut.printComment(results.toString());
}
You can add the row number at each row iteration like this:
for (int i = 0; i < row; i++) {
results += i + 1; // add the row number
for (int j = 0; j < col; j++) {
results += " " + pieces[board.board[i][j] + 2];
}
OthelloOut.printComment(results);
results = "";
}

Categories

Resources