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.
Related
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
I am trying to make a java program to print the Pascaline triangle. But it is not working properly. The code is provided below :
int rows=10;
int[] array=new int[10], temp=new int[10];
array[0]=1;
temp[0]=1;
System.out.println(1);
for(int i=1;i<rows;i++)
{
for(int j=1;j<=i;j++)
{
temp[j]=array[j-1]+array[j];
}
for(int term:temp)
{
System.out.print(term+"\t");
}
System.out.println();
array=temp;
}
It is giving the following output :
1
1 1
1 2 3
1 3 5 5
.....
Please tell what's wrong with the code.
Pascaline triangle is not factorial serial
A proposal is (warning I am not a Java programmer, please don't be rude with me if something is stupid / can be improved easily) :
public class Pascaline {
public static void main(String args[]) {
int n = 10, i, j;
int [] f = new int[n];
f[0] = 1;
for (i = 1; i != n; i++)
f[i] = f[i - 1] * i;
for(i = 0; i < n; i++) {
for(j = 0; j <= i; j++)
System.out.print((f[i] / (f[i - j] * f[j])) + " ");
System.out.println();
}
}
}
Compilation and execution :
pi#raspberrypi:/tmp $ javac Pascaline.java
pi#raspberrypi:/tmp $ java Pascaline
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
and to be a little prettier :
public class Pascaline {
public static void main(String args[]) {
int n = 10, i, j;
int [] f = new int[n];
f[0] = 1;
for (i = 1; i != n; i++)
f[i] = f[i - 1] * i;
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((f[i] / (f[i - j] * f[j])) + " ");
System.out.println();
}
}
}
Compilation and execution :
pi#raspberrypi:/tmp $ javac Pascaline.java
pi#raspberrypi:/tmp $ java Pascaline
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
Multiplication table for 2 only
This is my code:
public class nest
{
public static void main (String[] args)
{
for (int row=1; row<=5; row++)
{
for (int column=1; column<=10; column++)
{
System.out.print(row*++column +"\t");
}
System.out.println();
}
}
}
This is my target results:
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
42 44 46 48 50
But I'm getting this:
2 4 6 8 10
4 8 12 16 20
6 12 18 24 30
8 16 24 32 40
10 20 30 40 50
Help me please I'm still learning Java.
The trick here is in being able to articulate a formula for the value in each cell given a row and column index. Assuming we count both row and column starting from zero, then the formula is:
(2 + 10*row + 2*column)
This formula says that, starting with an initial value of 2, we increase by 10 moving down a row, and we increase by 2 moving to the right of a column. This leads to the following code:
for (int row=0; row < 5; ++row) {
for (int column=0; column < 5; column++) {
System.out.print((2 + 10*row + 2*column) + "\t");
}
System.out.println();
}
Demo
To make it simple you can do something like this:
public class A{
public static void main(String[] args){
int k=2;
for (int row=1; row<=5; row++)
{
for (int column=1; column<=5; column++)
{
System.out.print(k+"\t");
k=k+2;
}
System.out.println();
}
}
}
Similar to the above one. A simple one.
public static void main(String[] args) {
int tableOf = 2;
int currIter = tableOf;
for(int i = 1; i <= 5 ; i++) {
currIter = tableOf * i;
for(int j = 1; j <= 5 ; j++) {
System.out.print((currIter * j) + "\t");
}
System.out.println();
}
}
You can achieve your results by using an extra variable.
public class nest
{
public static void main (String[] args)
{ int table= 0;
for (int row=1; row<=5; row++)
{
for (int column=1; column<=5; column++)
{
table+=2;
System.out.print(table +"\t");
}
System.out.println();
}
}
}
the loops can be used to define rows and columns for printing table . hope it helped you a little.
You could also try (assuming you're using Java 8+), a formula based on breaking lines every five elements using a lambda and a ternary we can do so in a single statement. Generate a range of 1 to 25, multiply each value in the range by 2, and then print it (and if it isn't a multiple of 5 a tab, otherwise a newline). Like,
IntStream.rangeClosed(1, 25).map(i -> i * 2)
.forEachOrdered(i -> System.out.print(i + ((i % 5 != 0) ? "\t" : "\n")));
Your java code is great! It appears that you're just having a little bit of math logic problems.
Lets take a look at the following:
1 2 3 4 5
1
2
3
4
5
These are your rows and columns as you itterate through them in your loops.
2 4 6 8 10
Should be your first line which it is!
12 14 16 18 20
Should be your second line. Well lets take a look at your equation.
row*++column
++column means column + 1 = 2
1 * 2 is 2
we want 12
If we keep the range of the loops within 5 its much simpler.
public class nest
{
public static void main (String[] args)
{
for (int row=1; row<=5; row++)
{
for (int column=1; column<=5; column++)
{
System.out.print(logic math stuff +"\t");
}
System.out.println();
}
}
}
Looking at the expected output the numbers are just 1 - 25 * 2
Lets try to print 1 - 25 first.
Column itterates 1 - 5 so the first row is just column.
System.out.print(column + "\t");
1 2 3 4 5
Easy enough. So now on the second row we need 6 7 8 9 10.
Column is still 1 - 5 but row is now 2
The first number is supposed to be 6 so how do we get there?
row = 2
column = 1
Our column width is 5 so every itteration of row we have to add 5 * (row-1).
System.out.print((column + 5 * (row-1)) + "\t");
This prints 1 - 25 in 5 rows
Now double it!
System.out.print((column + 5 * (row-1)) * 2 + "\t");
I wrote simple code on random permutation between 1 to 10 using ArrayList. How can I make ArrayList in my file SmartPermutationGenerator to print the result by size of 10 in a console to get output as below:
I don't want this output:
Random arrays using Smart Force:
8 4 8 1 8 4 10 8 4 1 7 8 4 1 10 5 8 4 1 10 7 2 8 4 1 10 7 5 9 8 4 1 10 7 5 2 6 8 4 1 10 7 5 2 9 3 8 4 1 10 7 5 2 9 6
I want this output instead:
Random arrays using Smart Force:
8 4 8 1 8 4 10 8 4 1
7 8 4 1 10 5 8 4 1 10
7 2 8 4 1 10 7 5 9 8
4 1 10 7 5 2 6 8 4 1
10 7 5 2 9 3 8 4 1 10
7 5 2 9 6
Should limit the solution using arraylist only, don't want to use recursion.
This is my file SmartPermutationGenerator
import java.util.ArrayList;
import java.util.Random;
public class SmartPermutationGenerator
{
private int size;
private Random rand = new Random();
public SmartPermutationGenerator()
{
this.size = 10;
}
public ArrayList nextPermutation()
{
ArrayList<Integer> unused = new ArrayList<Integer>();
for (int i = 0; i < size; i++) // loop for element in array
{
unused.add(i + 1);
}
ArrayList<Integer> perm = new ArrayList<Integer>();
for (int k = 0; k < size; k++) //loop for random number between 1 to 10
{
int pos = rand.nextInt(unused.size());
perm.add(unused.get(pos));
unused.remove(pos);
System.out.print(perm.get(k) + " ");
for (int j = 0; j < k; j++)
{
System.out.print(perm.get(j) + " "); //loop for permutation 10 times
//System.out.println();
}
}
return perm;
}
}
This is my file BrutePermutationGenerator
import java.util.Random;
public class BrutePermutationGenerator
{
private int[] num = new int[10];
public int[] nextPermutation()
{
Random rand = new Random();
for (int j = 0; j < 10; j++)//loop for permutation 10 times
{
for (int i = 0; i < 10; i++)//loop for random number between 1 to 10
{
int low = 1;
int high = 10;
int range = high - low + 1;
int r = rand.nextInt(range);
num[i] = num[r];
num[r] = i;
}
for (int i = 0; i < 10; i++)// loop for element in array
{
System.out.print(num[i] + 1 + " ");
}
System.out.println();
}
return num;
}
}
This is my main file PermutationGeneratorViewer
public class PermutationGeneratorViewer
{
public static void main(String[] args)
{
BrutePermutationGenerator brute = new BrutePermutationGenerator();
SmartPermutationGenerator smart = new SmartPermutationGenerator();
System.out.println("\n" + "Random arrays using Brute Force: ");
brute.nextPermutation();
System.out.println("\n" + "Random arrays using Smart Force: ");
smart.nextPermutation();
}
}
You can use the modulus operator (%) in the printing loops to see if the index is a multiple of ten. If it is, print a newline.
Something like this would work:
for(...){
System.out.print(...);
if(count%10==0 && count!=0){ // if the index of the number is a multiple of 10 but not the first number
System.out.println(); // print a newline to separate rows
}
}
This will add a newline after the 10th, 20th, 30th, etc. numbers.
Another excellent solution is to create function for permutation to be repeated in file SmartPermutationGenerator as below:
public ArrayList<Integer> getRandomPermutation()
{
ArrayList<Integer> unused = new ArrayList<>();
.
.
.
}
public void nextPermutation()
{
for(int i = 0; i < size; i++) //loop for permutation 10 times
{
for(Integer item : getRandomPermutation())
{
System.out.print(item + " ");
}
System.out.println();
}
}
Solution credited to Mr.Soleh Abd Wahab.
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..!!