Calculating a sum within an array index in Java - java

Solution: I was using sum elsewhere, and my second variation of the code doesn't update it so the issue appeared later in my code. Rather silly, and embarrassing but oh well!
This is a block of working Java code:
int sum = 0;
for (int r = 0; r < k; r++) {
sum += matrix[r][c];
}
totals[0][c] = sum;
k elements in row r are summed together in sum, which is then stored in totals at the appropriate index.
My question is, why can't I have my code like this?
for (int r = 0; r < k; r++) {
totals[0][c] += matrix[r][c];
}
Where instead of using a separate integer sum I simply calculate said sum in the correct index of totals? This produces a different and very much wrong output. Would this be a good or bad practice? For clarification totals is initialised to all 0 by this point.
I have a feeling that I'm missing something rather simple but I'm struggling to find any useful information on the topic, including what I've found on the nature of arrays in Java.

To breakdown your code:
totals[0][c] += matrix[r][c];
means,
totals[0][c] = totals[0][c] + matrix[r][c];
So now, consider from your very first iteration of for loop, you don't want to add any value previously stored in totals[0][c] right?
Now, what is the way to avoid and do the same thing in that way? just initialize to 0 before adding to it.
totals[0][c] = 0;
for (int r = 0; r < k; r++) {
totals[0][c] += matrix[r][c];
}

You need to initialize the values of totals[0][c] = 0.
To do this, you can do the following when creating the matrix:
Float[] array = new Float[c];
Arrays.fill(array, 0f);
totals.add(array);
for (int r = 0; r < k; r++) {
totals[0][c] += matrix[r][c];
}

I was using sum elsewhere in my code, which I had originally read as being a new sum and not the original. As my second variation of the code was not updating sum, the second use of it was therefore incorrect. Silly mistake on my part, but live and learn.

Related

2D array filling | ArrayIndexOutOfBoundsException error

good afternoon! hi all! 1st time posting
for my assignment we are filling arrays using arithmetic and nested for loops. i've done a complete filling of a 2D array before using prime numbers, although i think i'm messing up somewhere..
when doing the line int priorNum = arr[r-1][c]; (see full code below) i run into an exception. i am trying to overwrite other lines in my array with this new equation, but must i be stopped by this utmost unchivalrous java error.
the error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 10
my array: int[][] arrayDimension = new int[10][6];
public static void populate2D (int[][] arr) {
//hardcode in values first :)
//and then peek up one row, but you can't go above the original row
arr[0][1] = 10;
arr[0][2] = 100;
arr[0][3] = 500;
arr[0][4] = 1000;
arr[0][5] = 5000;
int count = 0;
//for each row..
for (int r = 0; r < arr.length; r++) { //for each row
for ( int c = 0; c < arr[r].length; c++) { //for each column
arr[r][0] = count;
//never navigate out of bounds
//row 0 is where we're at.. how to populate further rows..?
int priorNum = arr[r-1][c];
int nextNum = priorNum * 2;
arr[r][c] = nextNum;
//can't look back .. SO go UP one.. which is r - 1 goes back one.. and then the length goes - 1
//when c is - peek UP a row < and enter last column.. ^
}
count++;
}
}
i left in some notes that i wrote if you can understand what i'm trying to go for :)
i can also offer this printArray method i wrote for any testing you'd like to try!
public static void print2DArray(int[][] arr) {
for ( int r = 0; r < arr.length; r++) {
for ( int c = 0; c < arr[r].length; c++) {
System.out.print(arr[r][c] + "\t");
}
System.out.println();
}
}
}
thank you for any replies / assistance! everyone here seems very nice, i could not find my type of question that deals with my answer so i felt bad about posting hehe
The problem I can see is that in the first iteration when int priorNum = arr[r-1][c]; gets executed, r = 0, as specified by your outer for loop.
So you are basically trying to access an element of your 2D array using a negative index, which will result in an ArrayIndexOutOfBoundException being thrown.
You could adopt an if statement that will handle the first iteration so that you will not access a prior index.
You could also look at the Array access section of the following article:
https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html
Hope this helped.

Looking for an efficient way to update multi-dimensional arrays

I update the values of a multi-dimensional array (Y[i][t][k]). Since the update needs to be done over many iterations, the runtime of this part of the code is really important. I was wondering if anyone knows how to do this in a more efficient way.
Below is the part that needs to be updated.
double [][][] Y=new double [a.length][b.length][c.length];
for(int i=0;i<a.length;i++){
for(int j=0;j<b;j++){
for (int k=0; k<c.length; k++){
if(i==w && j==r && k==u){// w, r and u can have any value.
Y[i][j][k]=g;
}else{
Y[i][j][k]=f;
}
}
}
}
Note that:
a is int [][].
b is int.
c is int [][].
q is double.
YIN is double [][][].
F is double.
g=q*YIN[i][j][k]+(1-q)*(Y[i][j][k]-F)
f=q*YIN[i][j][k]+(1-q)*(Y[j][j][k])
You are setting every element of a region of your multidimensional array, at a cost proportional to the number of elements set, so there's no reason to think that you can do it asymptotically better. However, it is likely that you can get some speed increase by using bulk-operation methods, and by handling the special case outside the loop instead of testing for it on every iteration. For example,
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
Arrays.fill(Y[i][j], 0, c.length, f);
}
}
if (c.length > 10) {
Y[0][0][10] = g;
}
Of course, this assumes that f is a constant expression, or at least that every evaluation of it is equal to every other (in the sense of the == operator) and produces no side effects. In that case, it is probably a bit better yet to engage bulk copying in place of bulk setting where you can do so:
for (int i = 0; i < a.length; i++) {
Arrays.fill(Y[i][0], 0, c.length, f);
for (int j = 1; j < b.length; j++) {
System.arraycopy(Y[i][0], 0, Y[i][j], 0, c.length);
}
}
if (c.length > 10) {
Y[0][0][10] = g;
}
If expression f does not satisfy the requirements above, then the best you can do might be just to lift the special case out of the loop, without changing anything else. For some expressions f and / or g, even that might not be possible, in the sense that it could produce an inequivalent result. For example, this would be the case where one or both are stateful in some relevant way, such as by closing over a counter.
As I understand from your code, your goal is to set Y[0][0][10] to g and other elements to f.
So how about forgetting about crazy loops and doing like the following code ?
Arrays.fill(Y, f);
Y[0][0][10] = g;

Using Arrays.asList as the Argumentfor Collections.swap(). Is it possible?

This is my first question here, and I truly am not sure if I am doing something wrong, or if its even possible, I saw it suggested here on stack overflow, however I am not sure if it works for my specific situation.
I am doing a challenge on Hackerrank.com, and It is making me enter an Array(not an ArrayList) and it wants me to swap the items until they are all in ascending order.
I know I can use a temp variable to hold one of the values and swap it out, but I saw someone recommend to use Collections.swap and here is how I tried to implement it:
for (int i = 0; i < n; i++){
int numSwaps = 0;
for(int j = 0; j < n - 2; j++) {
if(a[j] > a[j+1]) {
Collections.swap(Arrays.asList(a), j,j+1);
numSwaps += 1;
}
totalSwaps += numSwaps;
}
if(numSwaps == 0) {
break;
}
}
Am i doing using it wrong? Or is it something that is just not possible?
Thank you very much!

Variable may not have been initizialized (java)

So I was trying to write a function for a ragged array; I may have got this entirely wrong, if so please explain why/how I went wrong. It took me ages to get this far and I have a feeling I've alreayd done it wrong.
I tried compiling it because I'm pretty sure currently it will work, however i'm getting the error "variable n may not have been initialized". My code so far is:
static double[][] exampleMatrix()
{
int n;
double[][] a = new double [3][];
a[0] = new double[n-1];
a[1] = new double[n];
a[2] = new double[n-1];
{
for (int i = 0; i < n-1; i++)
{
a[0][i] = 1;
a[2][i] = 1;
}
for (int i = 0; i < n; i++)
{
a[1][i] = - i - 1;
}
return a;
}
}
I'm probably missing something really really obvious, but i'm not sure what it is to initialize n.
EDIT: I have been told to make this work for a value n that is not yet given.. How would I do that? As in, the user is supposed to input the value of n, and be given an array in return.
Basically, my given question is to implement a function exampleMatrix that, given n, produces the array where all values in teh array a[0] is 1, and same for a[2], and then for a[1], be given a range of values from -1 down to -n for a[1][n-1]. This is what I have so far to calculate this, but I am guessing I have gone completely wrong?
You don't set any value to n. How will your program know how big to make the arrays and how many iterations to run in the for loops?
Method variables (unlike fields) cannot rely on the default value (0 in this case). As such n is not anything when it is declared
int n;
You need to state what n is at some point between declaring it and using it, for example.
int n;
n=7;
or
int n=7;
n not known at compile time
You can also pass n as a variable, if n is variable
static double[][] exampleMatrix(int n){
double[][] a = new double [3][];
a[0] = new double[n-1];
a[1] = new double[n];
a[2] = new double[n-1];
{
for (int i = 0; i < n-1; i++)
{
a[0][i] = 1;
a[2][i] = 1;
}
for (int i = 0; i < n; i++)
{
a[1][i] = - i - 1;
}
return a;
}
}
This method would then be used as
double[][] someMatrix= exampleMatrix(5); //<-- 5 is passed into the function and becomes n
Or you can calculate n in whatever way you see fit
Actually the Problem is with local variable
int n;
The scope of local variables is much narrower. Compiler knows when its getting used. Hence, forcing programmer to initialize the variable
You have to initialize it with any default value as int n=0;
I want to complement the above responses.
You have to take care with the static segments, because when a class load its static segments, the class don't assign default value, if you type:
public static int n;
in your class, the value depends on the programmer. this can throw an exception about initialized.

Java insert random integers into binary search tree

Im trying to insert random integers into a binary search tree.
this is what ive tried
for(i = 0; i <= insertAmount; i++)
{
myTree.insert((int)Math.random()*1000000+1);
}
I think im just inserting the same number. doesnt the + 1 change the value?
it should be like this:-
(int)(Math.random()*100000)+1
The reason being your (int)Math.random() is giving 0 always and multiplication with 100000 has no effect. Hence, you're always getting 1 thanks to your +1.
This may not be the reply to your query, but you can consider Using Random class.
new Random().nextInt(1000000)
Have this..
for(i = 0; i <= insertAmount; i++)
{
myTree.insert((int)Math.random()*1000000)+i;
}
You must replace the +1 with i.
hope it helps.
Try below code.
Random rndm = new Random();
int min =1;
int max = 10;
for(int i = 0; i <= 10; i++)
{
System.out.println(rndm.nextInt(max - min + 1));
}

Categories