Java pascal triangle initialization question - java

I have this code below as I saw from textbook
public static int[][] Pascal(int N) {
int[][] result = new int[N][]; // Build a grid with specific number of rolls
for (int i = 0; i < N; i += 1) {
result[i] = new int[i + 1]; // Build an empty row with length
result[i][0] = result[i][i] = 1;
for (int j = 1; j < i; j += 1) {
result[i][j] = result[i - 1][j - 1] + result[i - 1][j];
}
}
return result;
}
I have no question for how this Pascal triangle is achieved, all very clear.
However, I did learned before that to create an Array, length must be given,
for example, int[] A = int[]; will give me Error
It has to be int[] A = int[N]; or int[] A = int[]{1,2,3,etc.};
So when we create the array grid int[][] result = new int[N][];
How is it allow me to only specify the number of rows, but leave the length of each row with blank?
I did noticed that the length of each roll was defined later at result[i] = new int[i + 1];, I still don't understand why this grid is allowed to be initiated.
Thanks!

Related

How to traverse diagonally through two dimensional array in Java?

I have a m x n matrix mat and I need to return an array of all the elements of the array in a diagonal order.
Input: mat = [[1,2,3],
[4,5,6],
[7,8,9]]
Output: [1,2,4,7,5,3,6,8,9]
public int[] findDiagonalOrder(int[][] mat){
int rows = mat.length;
int cols = mat[0].length;
int[] result = new int[rows * cols];
for(int i = 0; i <= rows - 1; i++){
for (int j = 0; j <= cols - 1; j++) {
while(i >= 0) {
i = i - 1;
j = j + 1;
from this point I dont know what should I do. Do you have any tips / advices how to continue to solve it myself?
I'm trying to figure out how to solve this problem by myself.
I'm trying to start from the first row and first column and then continue to traverse the array diagonally.

After counting sort the result array has one more element (0) than the original one

So I have a problem, this method is supposed to sort an array of integers by using counting sort. The problem is that the resulting array has one extra element, zero. If the original array had a zero element (or several) it's fine, but if the original array didn't have any zero elements the result starts from zero anyway.
e.g. int input[] = { 2, 1, 4 }; result -> Sorted Array : [0, 1, 2, 4]
Why would this be happening?
public class CauntingSort {
public static int max(int[] A)
{
int maxValue = A[0];
for(int i = 0; i < A.length; i++)
if(maxValue < A[i])
maxValue = A[i];
return maxValue;
}
public static int[] createCountersArray(int[] A)
{
int maxValue = max(A) + 1;
int[] Result = new int[A.length + 1];
int[] Count = new int[maxValue];
for (int i = 0; i < A.length; i++) {
int x = Count[A[i]];
x++;
Count[A[i]] = x;
}
for (int i = 1; i < Count.length; i++) {
Count[i] = Count[i] + Count[i - 1];
}
for (int i = A.length -1; i >= 0; i--) {
int x = Count[A[i]];
Result[x] = A[i];
x--;
Count[A[i]] = x;
}
return Result;
}
}
You are using int[] Result = new int[A.length + 1]; which makes the array one position larger. But if you avoid it, you'll have an IndexOutOfBounds exception because you're supposed to do x-- before using x to access the array, so your code should change to something like:
public static int[] createCountersArray(int[] A)
{
int maxValue = max(A) + 1;
int[] Result = new int[A.length];
int[] Count = new int[maxValue];
for (int i = 0; i < A.length; i++) {
int x = Count[A[i]];
x++;
Count[A[i]] = x;
}
for (int i = 1; i < Count.length; i++) {
Count[i] = Count[i] + Count[i - 1];
}
for (int i = A.length -1; i >= 0; i--) {
int x = Count[A[i]];
x--;
Result[x] = A[i];
Count[A[i]] = x;
}
return Result;
}
Here you go: tio.run
int maxValue = max(A) + 1;
Returns the highest value of A + 1, so your new array with new int[maxValue] will be of size = 5;
The array Result is of the lenght A.lenght + 1, that is 4 + 1 = 5;
The first 0 is a predefinied value of int if it is a ? extends Object it would be null.
The leading 0 in your result is the initial value assigned to that element when the array is instantiated. That initial value is never modified because your loop that fills the result writes only to elements that correspond to a positive number of cumulative counts.
For example, consider sorting a one-element array. The Count for that element will be 1, so you will write the element's value at index 1 of the result array, leaving index 0 untouched.
Basically, then, this is an off-by-one error. You could fix it by changing
Result[x] = A[i];
to
Result[x - 1] = A[i];
HOWEVER, part of the problem here is that the buggy part of the routine is difficult to follow or analyze (for a human). No doubt it is comparatively efficient; nevertheless, fast, broken code is not better than slow, working code. Here's an alternative that is easier to reason about:
int nextResult = 0;
for (int i = 0; i < Count.length; i++) {
for (int j = 0; j < Count[i]; j++) {
Result[nextResult] = i;
nextResult++;
}
}
Of course, you'll also want to avoid declaring the Result array larger than array A.

Adding jagged arrays beginner

I'm a beginner at java at struggling with this:
I am trying to sum two jagged arrays ( n and m, both double [][]) of the same size (each is length 3 at the first level, then of length x-1,x and x-1 respectively at the second level).
The problem I'm having is to specify the length that each array within the jagged array should be, at the moment my code is producing an n x n array because I've specified the length as n[1] rather than as a parameter, but if I try and use sum[i].length=n[i].length I get the error, "cannot assign value to final variable". So I know this part is wrong but I don't know what is right...
Thanks for the help!
My code:
else if (isValidTridiagonal(m)== true && isValidTridiagonal (n) == true)
{
int size = n[1].length; /** specifying all lengths to be x where they shouldnt be*/
sum = new double[3][size];
for (int i = 0; i < n.length; i++)
{
for(int j = 0; j< n[i].length; j++)
{
sum [i][j]= n[i][j] + m [i][j];
}
}
return sum;
}
There is some missing information. As far as I can tell there are two things you need to fix. You seem to have "sum" as a final variable already defined in your code.
Secondly, you are declaring a new array that is 3xsize big. If you want a jagged array in that sence, you must leave one of the brackets empty and in the first loop insert a new array of the wanted size.
double[][] sum = new double[3][]; //Make sure this is unique within the scope
for(int i = 0; i < 3; i++) { //if you want dynamic scaling you'll need to replace 3 in the array as well.
int size = n[i].length; //size of the new row
sum[i] = new double[size]; // Inserting a new array of the wanted size
for(int j = 0; j< sum[i].length; j++)
{
sum[i][j]= n[i][j] + m[i][j];
}
}
return sum;
The problem is probably with this line:
sum = new double[3][size];
Here you create an incorrect, non-jagged array of size [3][2]
When you try to set sum[1][2] (2nd, 3rd index), you will not be able to.
Otherwise, the code looks correct and I got a sum to work using this:
public static void main(String[] args) {
int[][] n = new int[3][];
n[0] = new int[2];
n[0][0] = 1;
n[1] = new int[3];
n[2] = new int[2];
int[][] m = new int[3][];
m[0] = new int[2];
m[1] = new int[3];
m[1][2] = 1;
m[2] = new int[2];
int[][] sum = new int[3][];
sum[0] = new int[2];
sum[1] = new int[3];
sum[2] = new int[2];
for (int i = 0; i < n.length; i++) { // n.length will be 3
for (int j = 0; j < n[i].length; j++) { // n[i].length will be 2, 3 and 2
sum[i][j] = n[i][j] + m[i][j];
}
}
System.out.println("Sum: ");
for (int i = 0; i < sum.length; i++) {
for (int j = 0; j < sum[i].length; j++) {
System.out.print(sum[i][j] + "|");
}
System.out.println();
}
}
This will print off:
Sum:
1|0|
0|0|1|
0|0|

fibonacci in Java

I am trying to create a program which finds the sum of even numbers below 4 million the Fibonacci sequence. I know there is a much simpler way of doing this, but I wanted to see if it would work with arrays. I have never really used arrays before as I am fairly new to Java, which is why I wanted to see if this worked with arrays. The main problem that I have is with the for statement. How would I see if the contents of fibarray[i] is less than 4000000?
Also, is it OK if I do the thing with the fibarray = new int[i]?
public static void main(String[] args) {
int[] fibarray;
int numcount = 0;
int i = 0;
long sum = 0;
fibarray = new int[i];
fibarray[0] = 0;
fibarray[1] = 1;
for(i = 0 , fibarray[i] < 4000000, i++;;){
fibarray[i] = fibarray[i - 1] + fibarray[i - 2];
}
}
I apologise if this sounds really stupid.
Any help would be much appreciated.
Thanks.
Well, you need to start your for loop with i = 2. And the for loop should be in this syntax
for(i = 2; fibarray[i] < 4000000; i++) {
fibarray[i] = fibarray[i - 1] + fibarray[i - 2];
}
See comments within the code:
public static void main(String[] args){
/*************************
* comments on your code
int[] fibarray; //use right java naming convention
int numCount = 0; //this variable is never used
int i = 0;
long sum = 0;
fibarray = new int[i];//you initialize an array of size 0.
fibarray[0] = 0; //you can't set value to array of size 0
fibarray[1] = 1; //you can't set value to array of size 0
//wrong syntax
for(i = 0 , fibarray[i] < 4000000, i++;;){
//use for(i = 0 ; fibarray[i] < 4000000; i++){
fibarray[i] = fibarray[i - 1] + fibarray[i - 2];
}
*******************************/
//Alternative code
//you don't need to keep all Fibonachi numbers found.
//you only use 3 numbers for every calculation
int size = 3;
int totalLimit = 4000000;
int[] fibArray = new int[size];
fibArray[0] = 0; fibArray[1] = 1;
int total = 0;
while( true ) {
fibArray[2] = fibArray[0] + fibArray[1] ;
if((fibArray[2]%2) ==0) { //even number
if((total + fibArray[2]) >= totalLimit) {
break;
}
total += fibArray[2];
}
fibArray[0] = fibArray[1] ;
fibArray[1] = fibArray[2] ;
}
System.out.println("Total "+ total );
}
Don't hesitate to ask for clarifications as needed.

How to reverse a Java array [duplicate]

This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 8 years ago.
I have this extremely simple program to reverse an array of integers but every time I try to run it, it just ignores the second loop where the reverse should happen and passes it or there maybe some trouble in it.
package chapter_1;
import java.util.*;
public class Reverse_array {
public static void main(String[] args) {
Scanner keybd = new Scanner(System.in);
int[] arr = new int[10];
for (int i = 0; i < arr.length; i++) {
System.out.println("[%" + i + "]=");
arr[i] = keybd.nextInt();
}
for (int i = 0; i < arr.length; i++) {
int temp = arr[i];
arr[i] = arr[10 - 1 - i];
arr[10 - 1 - i] = temp;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
}
}
}
it does not ignore the second loop, it simply should be
for (int i = 0; i < arr.length/2; i++) {
int temp = arr[i];
arr[i] = arr[10 - 1 - i];
arr[10 - 1 - i] = temp;
}
beacuse if you iterate from 0 to arr.length it will reverse Your array twice which in the end gives You back original array,
Just change arr.length to arr.length/2. Now you are reversing it twice.
You should browse your array until his half for not reversing twice ( -- => +).
Always try to use the array size to the browse.
for (int i = 0; i < arr.length; i++)
and not
for (int i = 0; i < 10; i++)
It's more general and correct. You can add a variable to save the array size.
So your code will:
package chapter_1;
import java.util.*;
public class Reverse_array {
public static void main(String[] args) {
Scanner keybd = new Scanner(System.in);
int arrayLenght = 10;
int[] arr = new int[arrayLenght];
for (int i = 0; i < arrayLenght; i++) {
System.out.print("%[" + i + "]= ");
arr[i] = keybd.nextInt();
}
for (int i = 0; i < arrayLenght / 2; i++) {
int temp = arr[i];
arr[i] = arr[arrayLenght - 1 - i];
arr[arrayLenght - 1 - i] = temp;
}
for (int i = 0; i < arrayLenght; i++) {
System.out.println(arr[i]);
}
}
}
I see that others gave you the solution as i'm writing.
Let me give you some suggestions:
-whatever you are trying, magane to keep the developing loop (error, modification, trial and again from start) as short as possible.
-insert data by hand rarely is a good option
so, in this case: better to avoid the first loop and put something like:int [] arr ={5,6,7,8,8,1,8,9,1,9};
-when in doubt fill the code with print so you can follow what the algorithm is doing,the next step will be learn to use the debugger but the first is the print instructions
-if you want to learn, try hard enough (it depends by you) before ask other's people help
Here is the problem
for (int i = 0; i < arr.length; i++) {
int temp = arr[i];
arr[i] = arr[10 - 1 - i];
arr[10 - 1 - i] = temp;
}
You make twice array elements swap
Instead, use
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}

Categories

Resources