I need to print out this shape using nested for loops for homework (full disclosure.)
I cant figure out how to center the whole thing though.
The periods represent a continuation of the pattern. So it's supposed to be the whole pyramid.
Here's what I have so now
public static void question4(){
int ix = 30;
for(int i = 1; i<=128; i=i*2){
// x is the number printed
//it gets the value from i,
for (int g = ix; g>=0; g--){
System.out.print(" ");
}
for (int x2 =1; x2<=i-1; x2=x2*2){
System.out.print(" ");
System.out.print(x2);
}
for (int x = i; x>=1; x=x/2){
System.out.print(" ");
System.out.print(x);
}
ix=ix-4;
System.out.println();
}
Thanks for the help with the decrementing spaces, now the numbers themselves push the bottom rows over however. I tried using the string.length command suggested by another user but it kept returning an error.
Try something like this:
public static void main(String[] args) {
String spacer = " ";
for (int i = 1; i <= 128; i = i * 2) {
// x is the number printed
// it gets the value from i,
System.out.print(spacer);
for (int x2 = 1; x2 <= i - 1; x2 = x2 * 2) {
System.out.print(" ");
System.out.print(x2);
}
for (int x = i; x >= 1; x = x / 2) {
System.out.print(" ");
System.out.print(x);
}
if ((i * 2) < 10)
spacer = spacer.substring(0, spacer.length() - 2);
else if ((i * 2) < 100)
spacer = spacer.substring(0, spacer.length() - 3);
else
spacer = spacer.substring(0, spacer.length() - 4);
System.out.println();
}
}
This will create space for each row decreasing the space as you go down the triangle.
Gives this for output:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
I know it is very easy to answer it. First check this code
int spaces = 7;
for(int i = 1; i<=128; i=i*2){
for(int k=1;k<=spaces;k++)
System.out.print(" ");
spaces--;
// x is the number printed
//it gets the value from i,
for (int x2 =1; x2<=i-1; x2=x2*2){
System.out.print(" ");
System.out.print(x2);
}
for (int x = i; x>=1; x=x/2){
System.out.print(" ");
System.out.print(x);
}
System.out.println();
}
As you can see whenever the first loop starts iterating, nested for loop for space start giving space before the another nested loop print the numbers. As the loop move further spaces will get decremented and your pyramid will grow eventually.
Although answered & accepted, here's a solution that prints a perfect pyramid with one for loop
public static void perfectPyramid() {
int upLimit = 1024;
int blankFieldWidth = String.valueOf(upLimit).length() + 1; // if upLimit is 3-digit, the blank field will be 4-blanks
String blank = new String(new char[blankFieldWidth]).replace("\0", " "); //one-liner for creating a String by repeating another String a given number of times
String numPart = "1" + new String(new char[blankFieldWidth - String.valueOf(blankFieldWidth - 1).length()]).replace("\0", " ");
String previous = "-"; // dummy initial value
for (int i = 1; i <= upLimit; i = i * 2) {
int countOfBlankFields = (int) (Math.log(upLimit / i) / Math.log(2)); // the count of blank columns per row (one side only)
String dynSpacer = new String(new char[blankFieldWidth - String.valueOf(i).length()]).replace("\0", " ");
numPart = numPart.replace(previous, previous + i + dynSpacer + previous);
String blanks = new String(new char[countOfBlankFields]).replace("\0", blank);
String row = blanks + numPart + blanks;
previous = i + dynSpacer;
System.out.println(row);
}
}
it prints a pyramid taking into account the spaces
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 256 128 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 256 512 256 128 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 256 512 1024 512 256 128 64 32 16 8 4 2 1
For what concerns the nested-loops, you can move from creating a row by replacing string into using a nested-for
Related
Hi so i have java loop problem.
So i'm trying to figure out how to determine the first number(in the top of the pattern) in the loop for floyd's triangle by entering the height on the triangle.
Note: only the height is to be inputted to determine the first number and the last number should be fixed to 1.
for example:
Enter the height: 5
The first number is: 15
15
14 13
12 11 10
9 8 7 6
5 4 3 2 1
Another one is
Enter the height: 6
The first number is: 21
21
20 19
18 17 16
15 14 13 12
11 10 9 8 7
6 5 4 3 2 1
I've figured out how to do the pattern and the decrementing of the value but i cant seem to figure out the first number. I've been trying to figure out the sequence but it's still confusing to me because i'm still new at java.
Here is my code:
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int n;
int startingnumber = ;
Scanner input = new Scanner(System.in);
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
System.out.print("The first number is "+startingnumber);
for(int i =1; i<=n; i++){
for(int j =1; j<=i; j++){
System.out.print(startingnumber);
startingnumber--;
}
System.out.println();
}
}
}
The code is still not finished because i cant figure out the formula :(
I would appreciate any help that i can find. Thanks!
This mathematical problem is Triangular number and here is a visual demonstration
S1 = 1
S2 = 1 + 2
S3 = 1 + 2 + 3
...
Sn = 1 + 2 + 3 + ... + n
=> 1 + 2 + 3 + ... + n = n * (n + 1) / 2
An also have a look at System.out.printf
public static void main(String[] args) {
int n;
int startingnumber;
Scanner input = new Scanner(System.in);
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
startingnumber = n * (n + 1) / 2;
System.out.println("The first number is " + startingnumber);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.printf("%3d ", startingnumber);
startingnumber--;
}
System.out.println();
}
}
Output
Enter the height of the triangle: 6
The first number is 21
21
20 19
18 17 16
15 14 13 12
11 10 9 8 7
6 5 4 3 2 1
The way you solve that type of question is by finding a mathematical relationship. In this case, you know (when input's 6) that the height's 6. You also know that at each row, you have one less number than at the one that goes after it. The bottom one has 6, as its the same as the height.
Therefore, you need to do 6+5+4+3+2+1 to obtain the starting number.
Now that formulated as a generic solution: n+(n-1)+((n-1)-1)..+1.
A possible implementation for that is:
System.out.print("Enter the height of the triangle: ");
n = input.nextInt();
int startingNumber = 0;
for (int i=n;i>0;i--) startingNumber+=i;
I'm trying to create a pyramid that will double all the way to the center.
The code is producing this.
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
import java.util.Scanner;
for (i = 1; i<= lines; i++){ // sets rows (lines)
for (j = a; j >= 1; j--){ // dead space on left
System.out.printf(str," ");
}
for (k = 1; k != i; k++){ //left side numbers
String str1 = "" + k;
System.out.printf(str, str1);
}
a--;
for (int l = k; l >=1; l--){ // right side numbers
String str2 = "" + l;
System.out.printf(str, str2);
}
}
I expected it to look like this.
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
k and l should be used as exponents rather than as the numbers you are printing.
int lines = 8;
String str = "%4s"; //pads each number to 4 spaces
for (int i = 1; i <= lines; i++)
{
for (int j = 0; j < lines - i; j++) //Replaced a with lines - i
{
System.out.printf(str, " ");
}
for (int k = 1; k != i; k++)
{
//replaced k with 2 ^ (k - 1)
String str1 = "" + (int)(Math.pow(2, k - 1));
System.out.printf(str, str1);
}
for (int l = i; l >= 1; l--)
{
//replaced l with 2 ^ (l - 1)
String str2 = "" + (int)(Math.pow(2, l - 1));
System.out.printf(str, str2);
}
System.out.println(); //added newline between each line
}
Output:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
Here is a solution that dynamically adjusts the spacing as needed.
The code uses <</>> bit-shifting to double/halve the numbers.
public static void printPyramidOfSquares(int lines) {
if (lines < 0 || lines > 63)
throw new IllegalArgumentException();
int width = Long.toString(1L << (lines - 1)).length();
for (int line = 1; line <= lines; line++) {
if (line < lines)
System.out.printf("%" + (lines - line) * (width + 1) + "s", "");
long val = 1;
for (int i = 1; i < line; i++, val <<= 1)
System.out.printf("%" + width + "d ", val);
for (int i = 1; i < line; i++, val >>= 1)
System.out.printf("%" + width + "d ", val);
System.out.printf("%" + width + "d%n", val);
}
}
Test
printPyramidOfSquares(4);
printPyramidOfSquares(5);
printPyramidOfSquares(8);
Output
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
Here is an alternative solution that calculates each row / col using the formula: "val = 2^(row - |lines - col - 1|)". It automatically adjusts the spacing using log base 10 to calculate the number of digits.
int s = 2 + (int) Math.log10(1 << lines);
IntStream.range(0, lines)
.mapToObj(r -> IntStream.range(0, 2 * lines - 1)
.map(c -> r - Math.abs(lines - c - 1))
.mapToObj(v -> v >= 0 ? String.format("%" + s + "d", 1 << v) : " ".repeat(s))
.collect(Collectors.joining()))
.forEach(System.out::println);
Overview
I'm sure this is a simple problem for most of you on here, but I have been struggling with a small spacing problem and was hoping I can learn from someone more experienced. I need to produce a triangle similar to the one below. You can see that the numbers are aligned correctly no matter the length.
Enter the number of lines: 8
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
My Code
Here is what I have so far. It isn't the prettiest, but it seems to give me the correct values at least.
import java.util.Scanner;
public class Pyramid2
{
public static void main(String[] args)
{
int i, j, k, l, a;
//Create a Scanner object
Scanner in = new Scanner (System.in);
//Prompt the user to enter number of rows in pyramid
System.out.print("Enter number of rows: ");
int rows = in.nextInt();
a = rows;
//Variables to determine length
int length = ("" + rows).length();
String str = " %" + length + "s";
//Logic
for (i = 1; i <= rows; i++)
{
for (j = a; j > 0; j--)
{
System.out.printf(str, " ");
}
for (j = 1; j <= (2*rows); j++)
{
if (j == (rows+1))
{
continue;
}
if (j < (rows+1))
{
k = j;
}
else
{
k = ((2*rows)-j+1);
}
if (k >= (rows+1-i))
{
l = (int)Math.pow(2, (i+k-rows-1));
String str1 = "" + l;
System.out.printf(str, str1);
}
}
a--;
System.out.println();
}
}
}
My Results
This is the console output when 6 rows are chosen. Everything looks good until row 5 when a 2 digit number (16) appears. What are some efficient ways to align the results properly?
Enter number of rows: 6
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
You calculate length as the number of digits in rows, but it needs to be number of digits in largest number in triangle.
E.g. for rows = 6, largest number is 32, so length should be 2.
For rows = 8, largest number is 128, so length should be 3.
Largest number is 2rows, which in Java means 1 << rows, so change length calculation to:
int length = ("" + (1 << rows)).length();
You are also adding one too many blanks on the left.
Change code to this:
a = rows - 1;
First of all i can recommend to determine the largest number in pyramid. Then count digits in this number. For 8 rows this number is 128, it has 3 digits. According this information we can decide that we need 3+1=4 (including spaces) characters to print every value in pyramid.
After it you have to complete every output number by spaces (from the left) to achive string size of 4 characters.
And the global prefix for every pyramid line will contain (rows - i) * 4 spaces.
Basically, the directions go as such:
Enter positive integer greater than 3 (n)
Program should print all possible pairs of positive integers greater than one whose product is <= to number entered (n)
Here is a sample output:
Enter an integer: 24
4 = 2 x 2
6 = 2 x 3
8 = 2 x 4
10 = 2 x 5
12 = 2 x 6
14 = 2 x 7
16 = 2 x 8
18 = 2 x 9
22 = 2 x 11
24 = 2 x 12
9 = 3 x 3
12 = 3 x 4
15 = 3 x 5
18 = 3 x 6
21 = 3 x 7
24 = 3 x 8
16 = 4 x 4
20 = 4 x 5
24 = 4 x 6
(Note: Products can appear more than once, but pairs should not)
For my solution, I started by determining the factors of n like so:
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int factors = 0;
System.out.println("Enter integer:");
int n = keyboard.nextInt();
for(int i = 2; i <=n ; i++) {
if(n % i == 0) {
System.out.println(i);
}
}
From there, it seems I should pull each factor and multiply it by an incremented variable starting at 2 until it is equal to or exceeds (n). I started to thing maybe this was incorrect, so I tried something like this instead:
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter integer:");
int n = keyboard.nextInt();
int index = 2;
int multiplier = 2;
int result = 0;
while(result < n) {
result = multiplier * index;
System.out.println(result);
index++;
}
Which works, but only for result 4 - 24, as multiplier never increments two 3. Is the actual solution just a hybrid of these possible solutions? Guidance in the correct direction would be appreciated, thank you!
I think your current approach is off, and in particular is missing one critical element to solving this: a double loop. I think the easiest way to handle this is to loop twice and generate all pairs meeting the requirements.
int number = 24;
for (int i=2; i < (int)Math.ceil(Math.sqrt(number)); ++i) {
for (int j=i; j <= number / 2; ++j) {
int pair = i * j;
if (pair <= number) {
System.out.println(pair + " = " + i + " x " + j);
}
}
}
The tricky part here was in determining the bounds for the two for loops. The second loop variable starts with the value of the first, and can get as large as half the input number. This is because the widest pair would occur when the first number be 2, forcing the second number to be the input halved. The bounds on the first loop are a bit more complex. We used the ceiling of the square root as the bounds, because the largest it can ever be would occur when both numbers are the same.
Try something like this.
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter integer: ");
int n = keyboard.nextInt();
for (int i = 2; i <= n / 2; i++) {
for (int j = 2; i * j <= n; j++) {
System.out.println(i + " x " + j + " = " + (i * j));
}
}
The result as follows.
Enter integer: 24
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
2 x 11 = 22
2 x 12 = 24
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
7 x 2 = 14
7 x 3 = 21
8 x 2 = 16
8 x 3 = 24
9 x 2 = 18
10 x 2 = 20
11 x 2 = 22
12 x 2 = 24
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
I need to make this pyramid using nested for loops,
so far all I have figured out is that I need three for loops.
I know how for loops work and have a pretty good grasp on the fundamentals of java, but I have no earthly idea on how this works.
Just wrote this without debug but it should produce this pyramid:
0
0 1 0
0 1 2 1 0
0 1 2 3 2 1 0
int pyramidHeight = 4;
for(int i = 0; i < pyramidHeight;i++){
for(int j = 1; j < pyramidHeight*2;j++){
if( j < pyramidHeight - i || j > pyramidHeight + i ){
System.out.print(" ");
}
else{
System.out.print(i - Math.abs(pyramidHeight - j));
}
System.out.print(" ");
}
System.out.println();
}
With two simple changes you should get your pyramid.
This should work! Note that you have each row counting total 2*i+1 elements where i is your current row number.
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int lim = 5;
int spaceLim = lim*2;
for (int i=0; i < lim; i++){ // Number of rows is the key here (pow 2)
String s = "%" + spaceLim + "s";
System.out.printf(s, "");
if (i == 0){
System.out.print(1);
}
else{
for (int j=0; j<i; j++) {
System.out.printf("%1.0f ",(Math.pow(2.0, (double)(j))));
}
for (int j=i; j>=0; j--){
System.out.printf("%1.0f ", (Math.pow(2.0, (double)(j))));
}
}
System.out.println();
spaceLim -= 2;
}
}
}
The demo of working solution is here - http://ideone.com/J2fcQw