Pascal Triangle Not Printing Correctly in Java? - java

I got an assignment that requires us to print out pascal's triangles based on the user entered value of N. We were provided a main that allows the user to calculate Pascal’s Triangle based on a value of n. In this case if n is 0, then Pascal’s Triangle is 1. Otherwise for n being greater than 0, the appropriate Pascal’s Triangle will be created and displayed. Here is the main:
public class CSCD210Lab13
{
public static void main(String[] args)
{
int n = 0;
int [][] pascal = null;
do
{
n = Lab13Methods.readN();
pascal = Lab13Methods.createPascalsTriangle(n);
Lab13Methods.printPascals(pascal);
}while(MyUtil.goAgain());
}// end main
}// end class
Here is my Methods file:
import java.util.*;
public class Lab13Methods
{
public static int readN()
{
Scanner kb = new Scanner(System.in);
System.out.println("Enter N: ");
int n = kb.nextInt();
while(n < 0)
{
System.out.println("Number Below 1. Re-Enter: ");
n = kb.nextInt();
}
return n;
}
public static int[][] createPascalsTriangle(int n)
{
int[][]pascalTri = new int[n + 1][(n + 1) * 2];
int sideOne, side;
pascalTri[0][n - 1] = 1;
sideOne = side = n - 1;
for (int y = 1; y < n; y++)
{
pascalTri[y][sideOne] = 1;
pascalTri[y][side] = 1;
sideOne--;
side++;
for (int k = 1; k <= y; k++)
{
int left = pascalTri[y - 1][sideOne + (2 * k) - 1];
int right = pascalTri[y - 1][sideOne + (2 * k) + 1];
pascalTri[y][sideOne + (2 * k)] = left + right;
}
}
return pascalTri;
}
public static void printPascals(int[][]pascal)
{
for (int f = 0; f < pascal.length; f++)
{
for (int v = 0; v < pascal[f].length; v++)
{
if (pascal[f][v] == 0)
{
System.out.print("");
}
else
{
System.out.print(pascal[f][v]+" ");
}
}
System.out.println();
}
}
}
Here is my goAgain file:
public static boolean goAgain()
{
boolean goAgain = false;
String answer;
Scanner kb = new Scanner(System.in);
System.out.println();
System.out.print("Do you want to go again? ");
answer = kb.nextLine();
while(!answer.equalsIgnoreCase("yes") && !answer.equalsIgnoreCase("no"))
{
System.out.print("Invalid Input. Do you want to go again? ");
answer = kb.nextLine();
}
if(answer.equalsIgnoreCase("yes"))
{
goAgain = true;
}
else if(answer.equalsIgnoreCase("no"))
{
goAgain = false;
}
return goAgain;
}
}
My question is about how it's printing. If I enter 10 to be the value of N, this is how it is supposed to print:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
However, this is how mine prints:
1
1 1 1 1
1 1 2 1 1
1 1 3 3 1 1
1 1 4 6 4 1 1
1 1 5 10 10 5 1 1
1 1 6 15 20 15 6 1 1
1 1 7 21 35 35 21 7 1 1
1 1 8 28 56 70 56 28 8 1 1
What am I doing wrong?

I think your error may be here:
pascalTri[y][sideOne] = 1;
pascalTri[y][side] = 1;
sideOne--;
side++;
Your program is designed to fill in the cells of the array in a checkerboard pattern:
for any two adjacent rows, one row will have non-zero entries only
in even-numbered locations, and the other will have non-zero entries
only in odd-numbered locations.
Notice that right after you do pascalTri[y][sideOne] = 1;, you decrement sideOne.
That means if you are in a row that should be using odd-numbered cells,
sideOne now is odd, but when you did pascalTri[y][sideOne] = 1;,
sideOne was still even. So you have put an even-numbered entry in a row that
should have only odd-numbered entries.
That is where all the extra 1s are coming from in your output.
Just delete these lines:
pascalTri[y][sideOne] = 1;
pascalTri[y][side] = 1;
All they are doing is creating those extra, unwanted 1 values. All the correct values
are being written in the array by other statements.

I don't know if you know what a pascal triangle is let me explain to you what it is.
11^0 = 1
11^1 = 11
11^2 = 121
11^3 = 1331
11^4 = 14641
11^5 = 161051
I don't know why have you done some much code all when you need was
public static void printPascalsTriangle(int n)
{
long number=11l;
for(int i=0;i<=n;i++)
{
System.out.println(new Double(Math.pow(number,i)).longValue());
}
}
You would need a case more that five which can be handled like this link.

Refer this short pascal code i have written which is depend on user input:
public class Pascal {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner= new Scanner(System.in);
System.out.println("Enter the Number of levels of Pascal");
int levelCount = scanner.nextInt();
for(int i =0;i<levelCount;i++) {
int value = 1;
for(int j=0;j<=i;j++) {
System.out.println(value);
value = value * (i - j) / (j + 1);
}
System.out.println("\n");
}
}
}
Enjoy..!!

Related

How do i fix the angle of my mathematical triangle of squares?

I need to fix my output as shown at the bottom, i have code that outputs the correct math values
but it does not output the correct angle that is expected of the example output that i have provided below. ( I know this is pretty simple for most of you stack users but im a beginner in java and this is something that confuses me ). I have not come up with any ideas on what i can do to fix this issue and put in the correct angle.
Instructions:
-Write a program using a Scanner that asks the user for a number
n between 1 and 9 (inclusive).
-The program prints a triangle with n rows.
-The first row contains only the square of 1, and it is right-justified.
-The second row contains the square of 2 followed by the square of 1,
and is right justified.
-Subsequent rows include the squares of 3, 2, and 1, and then 4, 3, 2
and 1, and so forth until n rows are printed.
Assuming the user enters 4, the program prints the following triangle to the console
1
4 1
9 4 1
16 9 4 1
Code:
import java.util.Scanner;
public class Triangle {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number between 1 and 9 inclusive:");
int n = scan.nextInt();
for (int i = 1 ; i <=n; i++) {
for (int j = n-i; j >=1; j--) {
System.out.print("");
}
for (int k = i; k <= n; k++ ) {
System.out.print(" " + i * i);
}
System.out.println(" ");
}
scan.close();
}
}
My output:
Please enter a number between 1 and 9 inclusive: 4
1 1 1 1
4 4 4
9 9
16
Here is a short and simple variant.
for (int row = 1; row <= n; row ++) {
for (int col = n; col >= 1; col--) {
if (col <= row) {
System.out.print(String.format("%2d ", col * col));
} else {
System.out.print(" ");
}
}
System.out.println();
}
Here is the output generated for input 9:
1
4 1
9 4 1
16 9 4 1
25 16 9 4 1
36 25 16 9 4 1
49 36 25 16 9 4 1
64 49 36 25 16 9 4 1
81 64 49 36 25 16 9 4 1
TL;DR; Use a pen and paper for annoying logic problems.
The easiest way to do a problem like this is to write out the locations you're printing in terms of the variables you are iterating through. An extra variable, col helps us keep track of the current column opposite of the direction we are iterating from.
We can notice that the number just corresponds to the column position, squared, if we were counting columns from right to left.
We can also notice that the number of blank spaces is equal to n - one less than the current row iteration (since that starts at 0).
1
4 1
9 4 1
16 9 4 1
All of that nonsense aside, we can use String.format() to make the output even for double digit numbers.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number between 1 and 9 inclusive:");
int n = scan.nextInt();
for (int i = n; i > 0; i--) {
int col = 4;
// Print spaces
for (int j = 0; j < (i-1); j++) {
System.out.print(" ");
col--;
}
// Print numbers
for (int j = (i-1); j < n; j++) {
System.out.print(String.format("%2d", col*col) + " ");
col--;
}
System.out.println();
}
scan.close();
}
I have used the code you guys provided and it had some logical issues when inputting a number past 4 it would not square the triangle correctly and would only create the shape. I have solved the issue by adding a while loop and editing the for loops and not it outputs correctly.
Incorrect output:
Please enter a number between 1 and 9 inclusive: 8
9
4 9
1 4 9
0 1 4 9
1 0 1 4 9
4 1 0 1 4 9
9 4 1 0 1 4 9
16 9 4 1 0 1 4 9
Correct Code Given:
import java.util.Scanner;
public class AverageGrades {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number between 1 and 9 inclusive:");
int n = scan.nextInt();
for (int row = 1; row <= n; row ++) {
for (int col = n; col >= 1; col--) {
if (col <= row) {
System.out.print(String.format("%2d ", col * col));
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
My Code:
import java.util.Scanner;
public class TriangleTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter Number between 1 and 9 : ");
int n = scan.nextInt();
while(n < 0 || n > 9)
{
System.out.print("Please enter a valid value between 1 and 9 :");
n = scan.nextInt();
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j <= n*2-(i + i); j++)
{
System.out.print(" ");
}
for(int l = i + 1; l > 0; l--)
{
int r = l*l;
System.out.print(r + " ");
}
System.out.println("\n");
}
scan.close();
}
}
Correct Output:
Enter Number between 1 and 9 : 10
Please enter a valid value between 1 and 9 :9
1
4 1
9 4 1
16 9 4 1
25 16 9 4 1
36 25 16 9 4 1
49 36 25 16 9 4 1
64 49 36 25 16 9 4 1
81 64 49 36 25 16 9 4 1

Why my Pascal's triangle code doesn't work?

I have been trying to write Pascal's triangle using a combination formula but it just doesn't work properly and I am not sure what the problem is?
Here's the input:
public class Probs {
public static int fact(int n) {
int f;
for (f = 1; n > 1; n--) {
f *= n;
}
return f;
}
public static int comb(int i, int j) {
return fact(i) / fact(i - j) * fact(j);
}
public static void main(String[] args) {
int n = 5;
int i;
int j;
for (i = 0; i < n; i++) {
for (j = 0; j < n - i; j++) {
System.out.print(" ");
}
for (j = 0; j <= i; j++) {
System.out.print(" " + comb(i, j));
}
System.out.println();
}
}
}
The Output:
1
1 1
1 2 4
1 3 12 36
1 4 24 144 576
Can you explain me why in a beginner-friendly way?
You need to add parentheses around the operations in comb() to get the correct precedence.
Both / and * have the same precedence, so when you write
return fact(i)/ fact(i-j)*fact(j);
This expression is actually equivalent to
return (fact(i)/fact(i-j)) * fact(j);
Which is not really what you want...
Fix it by adding parentheses around the product in the denominator:
return fact(i) / (fact(i-j)*fact(j));
Check your formula for getting the factorial. It should be:
factorial(i) / (factorial(i - j) * factorial(j))
Using streams, your code might look something like this:
public static int factorial(int n) {
return IntStream.rangeClosed(2, n).reduce((a, b) -> a * b).orElse(1);
}
public static int[][] pascalsTriangle(int n) {
return IntStream.range(0, n)
.mapToObj(i -> IntStream.range(0, i + 1)
.map(j -> factorial(i) / (factorial(i - j) * factorial(j)))
.toArray())
.toArray(int[][]::new);
}
public static void main(String[] args) {
int n = 10;
int[][] arr = pascalsTriangle(n);
pyramidOutput(arr);
}
public static void pyramidOutput(int[][] arr) {
String[] output = Arrays.stream(arr)
.map(row -> Arrays.stream(row).mapToObj(String::valueOf)
.collect(Collectors.joining(" ")))
.toArray(String[]::new);
int max = Arrays.stream(output)
.max(Comparator.comparing(String::length))
.orElse("").length();
Arrays.stream(output)
.map(row -> " ".repeat((max - row.length()) / 2) + row)
.forEach(System.out::println);
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
See also: How do I make this into a Pascal's triangle instead of a Right triangle?

Get a collection of positive integers adding up to n

Consider the “sums to n problem:” given a positive integer n, list all the different ways to get a collection of positive integers adding up ton. Assume that we don’t care about order, so 1 + 2 and 2 + 1 are the same possibility.For n= 3, the possibilities are1 + 1 + 1, 1 + 2, 3
import java.util.Scanner;
public class SumsToN {
static void listNumber(int arr[], int n, int i)
{
int MAX_POINT = 3;
if (n == 0)
{
printArray(arr, i);
}
else if(n > 0)
{
for (int k = 1; k <= MAX_POINT; k++)
{
arr[i]= k;
listNumber(arr, n-k, i+1);
}
}
}
static void printArray(int arr[], int m)
{
for (int i = 0; i < m; i++)
System.out.print(arr[i] + " ");
System.out.println();
}
public static void main (String[] args)
{
System.out.print("enter n number: " );
Scanner input = new Scanner(System. in);
int n = input.nextInt();
int size = 100;
int[] arr = new int[size];
System.out.println("list of all the possibilities of "+ n + " are");
listNumber(arr, n, 0);
}
}
My work is slightly incorrect as when i enter n = 5, it does not include for example 1 4
and also it orders are wrong like 1+1+2, not 1+2+1---i.e., "order doesn't matter
Can someone help me with this please?
$ java SumsToN
enter n number: 5
list of all the possibilities of 5 are
1 1 1 1 1
1 1 1 2
1 1 2 1
1 1 3
1 2 1 1
1 2 2
1 3 1
2 1 1 1
2 1 2
2 2 1
2 3
3 1 1
3 2
$ java SumsToN
enter n number: 3
list of all the possibilities of 3 are
1 1 1
1 2
2 1
3

Why won't my Pascal's Triangle java code work?

My question has been recently put on hold, so I decided to ask it again.
I have an assignment where my professor wants us to make Pascal's triangle on Java. He provided us a completed Main class that is supposed to work and we have to use it. We do not have to edit the Main class. The Main class is correct. It calls for the method where we have to write in our code. Also, I provided the correct output and the template of the Pascal class, which has the method I am supposed to fill in.
Here is the main class:
public class Main
{
public static void main(String[] args)
{
int n = args.length == 1 ? Integer.parseInt(args[0]) : 1;
for (int i = 1; i <= n; ++i)
{
int[] arr = Pascal.triangle(i);
System.out.print((i < 10 ? " " : "") + i + ": ");
for (int j : arr)
{
System.out.print(j + " ");
}
System.out.println();
}
}
}
My professor wants us to use his template of the Pascal class where we have to write in the code for the triangle method only. This is the only area where we have to write code for the assignment.
public class Pascal
{
public static int[] triangle(int n)
{
//My code goes here
return new int[]{0};
}
}
The output should be this:
1: 1
2: 1 1
3: 1 2 1
4: 1 3 3 1
5: 1 4 6 4 1
6: 1 5 10 10 5 1
7: 1 6 15 20 15 6 1
8: 1 7 21 35 35 21 7 1
9: 1 8 28 56 70 56 28 8 1
10: 1 9 36 84 126 126 84 36 9 1
Here is my Pascal class code:
public class Pascal
{
public static int[] triangle(int n)
{
int [][] pt = new int[n+1][];
for (int i = 0; i < n; i++)
{
pt[i] = new int[i + 1];
pt[i][0] = 1;//sets the position to 1
pt[i][i] = 1;
for (int j = 1; j < pt[i].length - 1; j++)
{
pt[i][j] = pt[i-1][j-1] + pt[i-1][j];
}
}
return new int[]{0};
}
}
My output:
1: 0
1: 10
1: 20
1: 1
1: 0
1: 0
Just return pt[n-1]; instead of a new empty array from the template (you are supposed to remove that line).
With that, it works for me, your algorithm is correct.

Pyramid Pattern in Java

It was so hard to ask such a newbie question on this advanced site. But after so much tries and even loosing my hope i was forced to bring my self here. I am not been able to print the following pattern:
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
But with my tiresome efforts i reached the following:
public static void main(String[] args) {
int num = 1;
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15 - i; j++) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print(num + " ");
}
System.out.println();
}
}
1
1 1
1 1 1
1 1 1 1
1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1
Here ya go
public static void main(String[] args) {
int max = 6;
int padLength = (int) Math.ceil(Math.log10(Math.pow(2, max) + 1)) + 2;
for (int i = 0; i < max; i++) {
for (int j = 1; j < max - i; j++) {
System.out.print(pad(" ", padLength));
}
for (int k = 0; k <= i; k++) {
System.out.print(pad(Math.pow(2, k), padLength));
}
for (int k = i - 1; k >= 0; k--) {
System.out.print(pad(Math.pow(2, k), padLength));
}
System.out.println();
}
}
public static String pad(double d, int l) {
Integer i = (int) d;
return pad(i.toString(), l);
}
public static String pad(String s, int l) {
return String.format("%-" + l + "s", s);
}
Explanation
int padLength = (int) Math.ceil(Math.log10(Math.pow(2, max) + 1)) + 2;
Math.pow(2,max) - Gives me maximal number I will have to display
Math.ceil(Math.log10(number + 1)) - I use this to determine length of string representation of specific number. Please refer to wikipedia to check what logarithm is. I add 1 to skip edge case when number is exact power of 10 e.g. log10(10)->1 (this will never occur in task specified in question, it's just for purity of solution). Ceil just rounds number up.
+2 - minimum gap between two numbers is specified example was 2 spaces long so I just add this
You could use here Integer.toString(((int)Math.pow(2, max))).length()+2 but it's not as pretty :)
return String.format("%-" + l + "s", s);
First I build format string that looks like e.g. %-3s, which means print String with minimum length of 3, padding on the right. Second argument is the String I want to print. Refer to documentation
Running example
I find the other answer very overwhelming and dramatic. You don't need much maths and complexity to solve this problem. This might not be the best code but I think it is easy to understand. Not even an explanation is needed, it is a row by row approach, It's good to keep things simple.
public static void main(String[] args) {
// Init
int row = 0;
int maxRows = 6;
int num = 1;
int indent = maxRows - 1;
// Printing loop
while (row < maxRows) {
// Indent
for (int i = 0; i < indent; ++i)
System.out.print(" ");
// Print nums
for (int i = 0; i < num; ++i)
System.out.printf("%4d", (int) Math.pow(2.0, i));
for (int i = num - 2; i >= 0; --i)
System.out.printf("%4d", (int) Math.pow(2.0, i));
// New line
System.out.println("");
// Adjustments
++row;
--indent;
++num;
}
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

Categories