Im currently writing some code that print Pascal's Triangle. I need to use a 2D array for each row but don't know how to get the internal array to have a variable length, as it will also always changed based on what row it is int, for example:
public int[][] pascalTriangle(int n) {
int[][] array = new int[n + 1][]
}
As you can see I know how to get the outer array to have the size of Pascal's Triangle that I need, but I don't know how to get a variable length for the row that corresponds with the line it is currently on.
Also how would I print this 2D array?
Essentially what you want to happen is get the size of each row.
for(int i=0; i<array.size;i++){//this loops through the first part of array
for(int j=0;j<array[i].size;j++){//this loops through the now row
//do something
}
}
You should be able to use this example to also print the triangle now.
This is my first answer on StackOverFlow. I am a freshman and have just studied Java as part of my degree.
To make every step clear, I will put different codes in different methods.
Say n tells us how many rows that we are going to print for the triangle.
public static int[][] createPascalTriangle(int n){
//We first declare a 2D array, we know the number of rows
int[][] triangle = new int[n][];
//Then we specify each row with different lengths
for(int i = 0; i < n; i++){
triangle[i] = new int[i+1]; //Be careful with i+1 here.
}
//Finally we fill each row with numbers
for(int i = 0; i < n; i++){
for(int j = 0; j <= i; j++){
triangle[i][j] = calculateNumber(i, j);
}
}
return triangle;
}
//This method is used to calculate the number of the specific location
//in pascal triangle. For example, if i=0, j=0, we refer to the first row, first number.
public static int calculateNumber(int i, int j){
if(j==0){
return 1;
}
int numerator = computeFactorial(i);
int denominator = (computeFactorial(j)*computeFactorial(i-j));
int result = numerator/denominator;
return result;
}
//This method is used to calculate Factorial of a given integer.
public static int computeFactorial(int num){
int result = 1;
for(int i = 1; i <= num; i++){
result = result * i;
}
return result;
}
Finally, in the main method, we first create a pascalTriangle and then print it out using for loop:
public static void main(String[] args) {
int[][] pascalTriangle = createPascalTriangle(6);
for(int i = 0; i < pascalTriangle.length; i++){
for(int j = 0; j < pascalTriangle[i].length; j++){
System.out.print(pascalTriangle[i][j] + " ");
}
System.out.println();
}
}
This will give an output like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Related
This is the original prompt:
Write program that declares a 2-dimensional array of doubles called scores with three rows and three columns. Use a nested while loop to get the nine (3 x 3) doubles from the user at the command line. Finally, use a nested for loop to compute the average of the doubles in each row and output these three averages to the command line.
Here is my code:
import java.util.Scanner;
public class Scorer {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double [][] scores = new double[3][3];
double value = 0;
int i = 0;
int j;
while (i < 3) {
j = 0;
while (j < 3) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
scores[i][j] = value;
j++;
}
i++;
}
int average = 0;
for (i = 0; i < scores.length; i++) {
for (j = 0; j < scores[i].length; j++) {
average += value;
value = value / scores[i][j];
System.out.println(value);
}
}
}
}
The part that I need help on is the nested for loop at the bottom of the code. This code is supposed to compute the average of the numbers that are entered; however, I am confused on how to do that with the nested for loop.
you're almost there!
Here are the things you need to do:
1)you've to initialize the variable 'average' after the first for loop.
because average needs to be 0 i.e., reset after second for loop ends each time.
2)you've defined "value = value / scores[i][j]" . I don't know why you did that, but "value = scores[i][j]" must solve your problem.
3) you should print the average only thrice i.e., after calculating average of each row. so, print average at the end of second for loop.
Hope this makes it clear.
here's the code for your reference:
for (i = 0; i < 3; i++) {
int average = 0;
for (j = 0; j < 3; j++) {
value = scores[i][j];
average += value;
}
System.out.println(average/3);
}
Ever i represents a row, every j represents a column.
You need the average of every row, meaning that for every same i and every different j for that i you need to store the values and calculate the average.
Looks like homework code. We can give you hints but not write it for you :(
I would like to fill a 3x3 2D array with values 1,2,3.
I need each number to appear for a given times.
For example:
1 to appear 2 times
2 to appear 4 times
3 to appear 3 times
What I need is to store this numbers to array in a random position.
For Example:
1,2,2
3,2,2
1,3,3
I already did this in a simple way using only 2 different numbers controlled by a counter. So I loop through the 2D array and applying random values of number 1 and number 2.
I'm checking if the value is 1 and add it in the counter and the same with number 2. if one of the counter exceeds the number I have set as the maximum appear times then it continues and applies the other value.
Is there any better approach to fill the 3 numbers in random array position?
See code below:
int [][] array = new int [3][3];
int counter1 =0;
int counter2 =0;
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
array[i][j] = (int)random(1, 3); //1,2
if (arrray[i][j]==1) {
counter1++;
} else if (array[i][j] ==2) {
counter2++;
}
//if it is more than 5 times in the array put only the other value
if (counter1>5) {
array[i][j] = 2;
}
//if it is more than 4 times in the array put only the other value
else if (counter2>4) {
array[i][j] = 1;
}
}
}
I finally did this according to this discussion:
How can I generate a random number within a range but exclude some?, with 1D array for tesing, but it does not always works.
Please see attached code:
int []values = new int[28];
int counter1=0;
int counter2=0;
int counter3=0;
for (int i=0; i<values.length; i++) {
if (counter1==14) {
ex = append(ex, 5);
}
if (counter2==4) {
ex =append(ex, 6);
}
if (counter3==10) {
ex =append(ex, 7);
}
values[i] = getRandomWithExclusion(5, 8, ex);
if (values[i]==5) {
counter1++;
} else if (values[i] ==6) {
counter2++;
} else if (values[i] ==7) {
counter3++;
}
}
int getRandomWithExclusion(int start, int end, int []exclude) {
int rand = 0;
do {
rand = (int) random(start, end);
}
while (Arrays.binarySearch (exclude, rand) >= 0);
return rand;
}
I would like to fill the 1D array with values of 5,6 or 7. Each one a specific number. Number 5 can be added 14 times. Number 6 can be added 4 times. Number 7 can be added 10 times.
The above code works most of the times, however somethimes it does not. Please let me know if you have any ideas
This is the Octave/Matlab code for your problem.
n=3;
N=n*n;
count = [1 2; 2 4; 3 3];
if sum(count(:,2)) ~= N
error('invalid input');
end
m = zeros(n, n);
for i = 1:size(count,1)
for j = 1:count(i,2)
r = randi(N);
while m(r) ~= 0
r = randi(N);
end
m(r) = count(i,1);
end
end
disp(m);
Please note that when you address a 2D array using only one index, Matlab/Octave would use Column-major order.
There are a ton of ways to do this. Since you're using processing, one way is to create an IntList from all of the numbers you want to add to your array, shuffle it, and then add them to your array. Something like this:
IntList list = new IntList();
for(int i = 1; i <= 3; i++){ //add numbers 1 through 3
for(int j = 0; j < 3; j++){ add each 3 times
list.append(i);
}
}
list.shuffle();
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
array[i][j] = list.remove(0);
}
}
You could also go the other way: create an ArrayList of locations in your array, shuffle them, and then add your ints to those locations.
I need to multiple all the values in an array by 3000 which in turn would create a new array that I will use to subtract from another array. I've tried to create a separate method that would do that for me but all I got back in the multiplied array was a bunch of numbers and symbols strangely?
here is the code that I wrote
public static void main(String[] args)
{
int numberOfTaxpayers = Integer.parseInt(JOptionPane.showInputDialog("Enter how many users you would like to calculate taxes for: ");
int[] usernumChild = new int[numberOfTaxPayers];
for (int i = 0; i < usernumChild.length; i++)
{
usernumChild[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter number of children for user "+ (i+1) +": "));
}//this for loop finds out the number of children per user so we can later multiply each input by 3000 to create an array that determine dependency exemption for each user
int[] depndExemp = multiply(usernumChild, 3000);//this was the calling of the multiply method... somewhere here is the error!!
}//end main method
public static int[] multiply(int[] children, int number)
{
int array[] = new int[children.length];
for( int i = 0; i < children.length; i++)
{
children[i] = children[i] * number;
}//end for
return array;
}//this is the method that I was shown in a previous post on how to create return an array in this the dependency exemption array but when I tested this by printing out the dependency array all I received were a jumble of wrong numbers.
In your example you're multiplying your children array but returning your new array. You need to multiply your new array by your children array.
1 public static int[] multiply(int[] children, int number)
2 {
3 int array[] = new int[children.length];
4 for( int i = 0; i < children.length; i++)
5 {
6 array[i] = children[i] * number;
7 }//end for
8 return array;
9 }
The reason you're getting strange symbols is because you are returning uninitialized values. The array itself is allocated at line 3 but at this point each index of the array has not been initialized so we don't really know what values are in there.
Using Java 8 streams it can be as simple as:
public static int[] multiply(int[] children, int number) {
return Arrays.stream(children).map(i -> i*number).toArray();
}
You really don't have to create new array in your method (and you are also returning the old one without any change). So just do
public static int[] multiply(int[] children, int number) {
for(int i = 0; i < children.length; i++) {
children[i] = children[i] * number;
}
return children;
}
You need to Change
children[i] = children[i] * number;
to
array[i] = children[i] * number;
If I understand your question correctly:
children[i] = children[i] * number;
Should be changed to
array[i] = children[i] * number;
Considering you are returning array, not children.
In your second for loop it should be :
for(int i = 0; i < children.length; i++){
array[i] = children[i] * number;
}//end for
Also make sure that all values of children[i] are inferior than ((2^31 - 1)/number) +1
I'm working on this code in my program right now and it seems that the problem is with the line where I stop the inner loop of the 2nd dimension.
this is a sample output of the array
9 6 6
7 6 4
4 8 5
when i run this code the output is:
4 4 6
5 6 6
7 8 9
my expected output is:
4 4 5
6 6 6
7 8 9
a digit:"6" is not in the correct place. Its because when I try to run the part where there is a nested for loop above a for loop, it only runs once and so it only checks the 1st column instead of getting to the third column where 6 is. The problem is I need to limit that loop in only reading the highest numbers from row#0 column#0 to row#2 column#0.
How do I solve this problem?? I thought of using a one dimensional array and put all two dimensional array elements and sort it there then put it back to the two dimensional array and print it again but that wouldn't make my code solve the needed process of sorting two dimensional array.
public static void sortArray(){
int x = len-1, y = len-1;
int iKey=0,jKey=0;
int cnt=0;
do{
cnt++;
if(y==-1){
x--;
y=len-1;
}
System.out.println(cnt+".)"+x+"-"+y);
int hi = -1;
for(i = 0;i <= x; i++)
for(j = 0;j <= y; j++){
if(twodiArray[i][j]>hi){
hi = twodiArray[i][j];
iKey = i;
jKey = j;
}
}
int temp = twodiArray[iKey][jKey];
twodiArray[iKey][jKey] = twodiArray[x][y];
twodiArray[x][y] = temp;
//dispArray();
y--;
}while(cnt<9);
}
The problem is in your loops where you search max element. Suppose you have array 5x5 and x=1 and y=1. Then you loop will check only following elements: [0][0], [0][1], [1][0], [1][1]. But it should also check [0][2], [0][3], [0][4].
With you previous code you only checked following cells:
XX...
XX...
.....
.....
.....
But you need to check these:
XXXXX
XX...
.....
.....
.....
So you need something like this:
for(i = 0;i <= x; i++) {
int upper; // How many elements we need to check on current row.
if (i != x) {
upper = len - 1; // We are not in last row, so check all elements.
} else {
upper = y; // On the last row we need to check only elements up to y.
}
for(j = 0;j <= upper; j++){
if(twodiArray[i][j]>hi){
hi = twodiArray[i][j];
iKey = i;
jKey = j;
}
}
}
My code checks every row fully until last one.
EDIT
If you use:
for (int i = 0; i <= x; i++) {
for (int j = 0; j <= y; j++) {
...
}
}
then you iterate only on recangle with upper left corner in (0,0) and right bottom cornar in (y,x). E.g. x = 4, y = 3:
XXX...
XXX...
XXX...
XXX...
......
But your goal is to do every row before last one fully. So check 0-th, 1-st and 2-nd rows fully and 3 elements from 3-rd row. My code does it. upper show how many values from row we need to check for all rows except last one it's equals to len - 1 (check full row). For last one it's y.
Your swap code (starting with int temp = twodiArray) is outside the main iteration loop. It needs to be moved inside the innermost loop.
BTW, you can do the swap without storing the indices.
Personally, to save myself some confusion, I would think of it as if it were a 1D array.
// I'm assuming that columnCount and rowCount are stored somewhere
public int getNthElement(int index) {
int colIndex = index % columnCount;
int rowIndex = (index - colIndex) / rowCount;
return twodiArray[rowIndex][colIndex];
}
public void setNthElement(int index, int value) {
int colIndex = index % columnCount;
int rowIndex = (index - colIndex) / rowCount;
twodiArray[rowIndex][colIndex] = value;
}
public void sortArray(int[][] array) {
int elementCount = rowCount * columnCount;
int curIndex = elementCount - 1;
while (curIndex >= 0) {
int highestIndex = -1;
int highestValue = 0;
for (int i = 0; i <= curIndex; i++) {
int nthValue = getNthElement(i);
if (nthValue > highestValue) {
highestIndex = i;
highestValue = nthValue;
}
}
int swapValue = getNthElement(curIndex);
setNthElement(curIndex, highestValue);
setNthElement(highestIndex, swapValue);
curIndex--;
}
}
You can see that I still use the 2D array and never use an actual 1D array, but this code indexes into the array as if it were a 1D array. (Hopefully that is valid in your professor's eyes)
I have this question:
The method accepts an integer array as its input and returns a new array which is a
permutation of the input array. The method fix34 rearranges the input array such
that every 3 is immediately followed by a 4 (e.g. if there is a 3 at position i, there will
be a 4 at position i+1). The method keeps the original positions of the 3s but may
move any other number, moving the minimal amount of numbers.
Assumptions regarding the input:
The array contains the same number of 3's and 4's (for every 3 there is a 4)
There are no two consecutive 3s in the array
The matching 4 for a 3 at some position i is at position j where j > i
ok, so this is what I wrote:
public class Fix34 {
public static void main(String[] args){
int [] args1 ={3,1,2,3,5,4,4};
int[] args11=fix34(args1);
for (int i = 0; i<=args11.length-1;i++ ){
System.out.print(args11[i]+" ");}}
public static int pos (int[] arr){
int i= arr.length-1;
while (arr[i]!=4){
i=-1;
}
return i;
}
public static int[] fix34(int[] nums){
for(int i = 0; i<=nums.length-1; i++){
if (nums[i] == 3){
nums[pos(nums)]=nums[i+1];
nums[i+1]=4;
}
}
return nums;
}
}
when I insert arrays such {3,2,1,4} it works, but with the array as written in the code, it gives me the error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at Fix34.pos(Fix34.java:15)
at Fix34.fix34(Fix34.java:25)
at Fix34.main(Fix34.java:6)
how come the arrays gets to -1 position?!
Thanks
you are setting it to -1 here:
i=-1;
Your issue in in this piece of code
public static int pos (int[] arr){
int i= arr.length-1;
while (arr[i]!=4){
i=-1;
}
return i;
}
If the last element in the array is 4 the while loop is never entered so arrays like 3, 1, 2, 4 are fine. Otherwise the loop is entered and i is set to -1. I think that you mean to decrement. In that case replace
i=-1
with
i--
or
i=i-1
and as mentioned in another answer make sure i doesn't go below 0.
I think you ment
i-= 1;
instead of that:
i=-1;
Whoa there that is a little overblown for this problem. Nested loops are they key hereā¦come take a look
public int[] fix34(int[] nums) {
for(int a = 0; a < nums.length; a++){ //we see 4's first
for(int b = 0; b < nums.length - 1; b++){ //then the nested loop finds a 3
//length - 1 to stay in bounds, although not needed here...
if(nums[a] == 4 && nums[b] == 3){
//swap
int tmp = nums[b + 1];
nums[b + 1] = nums[a];
nums[a] = tmp;
}
}
}
return nums;
}