I have the code below:
int lines = 0;
while(lines < 2)
{
int[] oldarr = parr;
for(int i = 0; i < arrsize; i++)
System.out.print(" " + oldarr[i]);
System.out.println();
for(int i = 0; i < arrsize; i++)
{
if(i == 0)
parr[i] = 0;
else
parr[i] = Math.abs(oldarr[i] - oldarr[i-1]);
}
lines++;
}
parr is an array of integers of size [arrsize]. Each time through this loop I want to print the value of each index in parr, then set each index to the difference between the index before it and itself. Currently it gives me the correct (hardcoded) originally parr. But the next(first) iteration of changing parr gives me unexpected values; they are not even close to the difference between the two neighboring values..
Any ideas?
You aren't copying your array with this line:
int[] oldarr = parr;
The two variables are still pointing at the same array.
To get a copy, you can do:
int[] oldarr = Arrays.copyOf(parr, parr.length);
In your second for loop, you are setting the new value to the difference of the current value and the previous value, but the previous value was already changed in the previous iteration of the for loop.
Change your second for loop iteration to iterate through the array backwards, so your calculations don't depend on previous calculations.
for(int i = arrsize - 1; i >= 0; i--)
Related
So in java, This is what I'm trying to execute:
num [0]=list.get(2);
num [1]=list.get(4);
num [2]=list.get(6);
num [3]=list.get(8);
I have an arraylist of integers called list and I want to put the values that are in the even number indices starting at 2 into an array of integers called num in the indices 0,1,2,3,etc. My problem is, I'm trying to do this within a for loop but I'm not sure how to go about it. Here is what I have:
for (int i=0; i<list.size()-2; i++){
num[i] = list.get(i+2);
}
My problem here is, after incrementing i, my arraylist goes to the next index also instead of every other index. I've tried multiple variations of this loop but I keep coming to the same problem.
This should do it:
int max = list.size()/2;
if(list.size()%2==0) max-=1; // prevents IndexOutOfBounds for even list lengths
for (int i=0; i<max; i++){
num[i] = list.get(i*2 + 2);
}
You can try something like this.
for (int i=0,j=0; i<list.size()-2; i+=2,j++){
num[j] = list.get(i+2);
}
The loop should continue as long as the i is less then (list.size()-1)/2
List<Integer> list = Arrays.asList(0,1,2,3,4,5,6);
int size = (list.size()-1)/2;
int[] num = new int[size];
for (int i=0; i<size; i++){
num[i] = list.get(i*2+2);
}
System.out.println("num="+ Arrays.toString(num));
Here is DEMO
This should work:
for(int i = 0; i < list.size() - 2; i++)
num[i] = list.get((i * 2) + 2);
I am working on an assignment where I need to create two arrays, then look through them and create a new array that holds any values inside of both the first two. Originally, I was close to accomplishing this by making an arraylist but my lab professor told me that wasn't allowed so I needed to re-start and didn't have enough time to figure out the solution.
If you'd like to see the whole code I have now: http://pastebin.com/thsYnj2z
I am really struggling with this loop here:
for(int i = 0 ; i < Xarr.length ; i++){
for(int j = 0 ; j < Yarr.length ; j++)
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
k++;
System.out.println(ArrA[k]);
break;
}
My output is remaining 0 for my ArrA[k] array. I can't seem to trouble shoot this issue on my own.
try making these changes
for(int i = 0 ; i < Xarr.length ; i++){
for(int j = 0 ; j < Yarr.length ; j++)
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
System.out.println(ArrA[k]); // or print them all later
k++;
break; // break to outer loop
}
}
}
note
Assuming OP has correctly initialized ArrA
note2
Assuming that only unique values are required, hence the breaking
Does your solution require that no values are duplicated in ArrA? Or are duplicate values allowed? For example, if some values occur multiple times in each array, you could get multiple matches on the same number.
If duplicates aren't a problem:
for(int i = 0 ; i < Xarr.length ; i++){
for(int j = 0 ; j < Yarr.length ; j++){
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
System.out.println(ArrA[k]);
k++;
}
}}
As I understand it, the problem is to take 2 arrays, and produce a third array which is a Union of the first 2. Union of 2 sets being the subset of the values found in both sets.
Your code was missing some braces, so put those back in there. Also you wont want to print the k+1th item after you just put a value in ArrA[k] im assuming.
Otherwise you were pretty much there. The break terminates the inner loop and allows the outer loop to increment i and continue on. This is because you have already found a match, no need to continue searching, just move onto the next index in Xarr.
Algorithm goes like this: For each value in X, search Y for a match. If it is found, add this value to A.
for(int i = 0 ; i < Xarr.length ; i++) {
for(int j = 0 ; j < Yarr.length ; j++) {
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
System.out.println(ArrA[k]);
k++; //you probably want to increment k after you add to ArrA, not before
break;
}
}
}
public static void main(String... args){
int[] xArr = {1, 1,1,1,1,1};
int[] yArr = {1, };
int[] kArr = new int[xArr.length > yArr.length ? xArr.length : yArr.length];
int k = 0;
for(int x = 0; x < xArr.length; x++){
for(int y = 0; y < yArr.length; y ++){
int xNum = xArr[x];
int yNum = yArr[y];
if(xNum == yNum) kArr[k++] = xNum;
}
}
int[] resizedKArr = new int[k];
for(int i = 0; i < resizedKArr.length; i++) resizedKArr[i] = kArr[i];
Arrays.sort(resizedKArr);
for(int x : resizedKArr) System.out.println(x);
}
First, xArr and yArr are given some random numbers, and then kArr is initialized with the size of the lagest array we are comparing with to ensure the array has enough space to hold similar values.
Then, in the next section we do a loop inside of a loop to compare the values against each other and if they are similar then k++ and set the next value in the array. This goes on until the loops are completed, notice there really is never a need to break from either loop until all values are compared. At that point the loops break themselves and move on to the next bit of code.
The last section is just to create an array of the same size as k and move the values over, I don't know the requirements of your studies, although when using primitives like this you may want to do this in case you have a matching 0 as a number. Otherwise you'll have a ton of 0s filling the empty spaces of your array.
And lastly, we just sort the array for good measure and print it out.
Hope I've answered your question and you get something out of this post!
The problem is printing ArrA[k] after k++. Try increasing line after print.
This question already has answers here:
How can I avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException? [duplicate]
(2 answers)
Closed 7 years ago.
Here is part of my code. I want to assign random number to the matrix population[][] first, then compare the random number to a specific number ranP, if population[][] < ranP, then re-assign population[][] to 1, otherwise 0. But it shows
arrayindexoutofboundsexception 0
Need help on the issue. Thanks!
randGen = new Random();
double randNum = randGen.nextDouble();
for ( int i = 0; i < 11; i++){
for (int k = 0; k < inipopulationsize; k++){
for (int j = 0; j < 25; j++){
ranP = 0.5;
//TMaxtrix[i][j] = matrix[i][j];
System.out.println(matrix[i][j] + " ");
population = new double[k][j];
System.out.println("randNum: " + randNum);
population[k][j] = randNum;
if (randNum <= ranP){
population[k][j] = 1;
}
else
population[k][j] = 0;
System.out.println("population: " + population[k][j]);
}//j loop
}//k loop
}//i loop
I am learning this by myself, and not taking any classes. If this really bothers you "experts", why dont you just ignore and save your time go home watching a movie or spending more time with your family? Appreciate the help from nice people here. But shame on you who only knows sarcasm. Here is what works finally:
randGen = new Random();
population = new int[inipopulationsize][25];
for ( int i = 0; i < population.length; i++){
for (int j = 0; j < population[i].length; j++){
double randNum = randGen.nextDouble();
ranP = 0.5;
if (i < 11){
//System.out.println(matrix[i][j] + " ");
}
if (randNum <= ranP){
population[i][j] = 1;
}
else
population[i][j] = 0;
//System.out.println("population index: " + i + " Dieasease index: " + j + " DI on (1) or off (0): " + population[i][j] + "");
}//j loop
}//i loop
Is the third loop because you want i 2d arrays? If so you should probably look at ArrayLists of 2d arrays.
int inipopulationsize = 25;
double[][] population;
Random randGen = new Random();
double randNum = randGen.nextDouble();
double ranP = 0.5;// outside loops
population = new double[inipopulationsize][25]; // out
for (int k = 0; k < inipopulationsize; k++){
for (int j = 0; j < 25; j++){
randNum = randGen.nextDouble();//i assume you want new random every time
if (randNum <= ranP){
population[k][j] = 1;
}
else
population[k][j] = 0;
}//j loop
}//k loop
System.out.println(Arrays.deepToString(population));
I don't see a reason for having 3 loops with a 2d array.
Random randGen = new Random();
double randNum;
for(int i=0; i<population.length; i++){
for(int j=0; j<population[i].length; j++){
randNum = ranGen.nextDouble();
if(randNum<0.5) population[i][j] = 0;
else population[i][j] = 1.0;
}//j loop
}//i loop
Your issue is that you are referring to an item outside the bounds of your 2D array.
Let's take a look at your code. This line: population = new double[k][j]; declares a new 2D arrays of size kxj. Then in this line: population[k][j] = randNum; you try to reference the item in the kth column and jth row of this same 2D array. This is not legal in Java arrays.
Java arrays are 0-indexed, which means with an array of size k, your indexes range from 0 to k-1. There is no item at index k. This is why you are receiving an index out of bounds error.
Please look at this link instructing you on the basic use of Java Arrays.
The exact error arrayindexoutofboundsexception 0 appears because on your first iteration, you create a population of size 0 by 0. Then you try to access the item in column 0 and row 0, that is to say, the first item. However as your population array has 0 size, it has no space, and even the index 0 is out of bounds.
However, I am not even sure this is what you want to be doing.
You are declaring a 2D array on each iteration of your loop. If all you are trying to do is make a single array of size inipopulationsizeby25 (these are the initial values of k and j) then you need to declare this outside of these two nested loops. Perhaps even outside of the third loop, as I am not even sure what that loop is doing.
Take a loop at anaxin's answer for how to effectively assign 0's and 1's to your population array randomly. (With randP set to 0.5 you are giving each a 50% chance of appearing.)
I have the following code from a previous past paper:
int n = arr.length;
double min = 0;
int minLocation=0;
for(int i = 1; i <= n; i++) {
if( arr[i] < min ) {
min = arr[i];
}
minLocation = i;
}
System.out.print("The minimal value is arr[");
System.out.println(minLocation + "] = " + min);
I have to answer the following questions from the code:
(i) The line on which the error appears
(ii) What effect the error would have
(iii) How the error should be corrected.
You may assume arr[] is a non-empty array of double values that has been
properly declared and initialized.
I know there will be a runtime error at the line with the if statement which i'm still not sure how. As I am unable to correct it I can't see how I get the undesired results. I can see it's such a straight forward question and I am missing out something extremely obvious but I have been looking at it for a while and i'm completely missing it.
There are several mistakes in that code. Here a list of them including explanation of impact and how to fix them:
You are initialising min with 0
Effect: If your array e.g. only consists of {1.1, 2.2} your code would claim that 0 is the minimum, what obviously is wrong because there doesn't exist an index i that arr[i] == 0
Fix: double min = Double.MAX_VALUE;
Your for-loop starts at index 1 for (int i = 1; ...)
Effect: You are skipping arr[0]
Fix: for (int i = 0 ...)
Your loop iterates once to often because of the condition or ( ... ; <= n; ...)
Effect: You will encounter an AIOOBE (ArrayIndexOutOfBoundsException)
Fix: for ( ... ; i < n; ...)
Your are overwriting minLocation in every iteration of the loop
Effect: After the last iteration of the loop, minLocation will always be = n
Fix: Place minLocation = i; inside the if-statement.
Corrected version
int n = arr.length;
double min = Double.MAX_VALUE;
int minLocation = 0;
for(int i = 0; i < n; i++) {
if(arr[i] < min) {
min = arr[i];
minLocation = i;
}
}
I know there will be a runtime error at the line with the if statement
which i'm still not sure how
This runtime error will be IndexOutOfBoundsException. This error occur because array index is one less than array size.
Your loop should be like.
for(int i = 0; i < n; i++)
Did you intend your for() loop to start at index 1? By convention it starts at 0;
It should really be: for(int i=0;i
Your for loop needs to be:
for(int i = 0; i < n; i++)
Otherwise you will get an IndexOutOfBoundsException since you access the array outside of its range.
Also you should change your min value initialiaztion to:
double min = Double.MAX_VALUE;
Otherwise you will only find the minimum if your array only contains negative values.
There are logical errors in your program, if it is intended to find the minimal value and position of given array.
Initialize
double min = arr[0];
End for loop at
i < n
Include
minLocation = i;
as
if( arr[i] < min )
{
min = arr[i];
minLocation = i;
}
Java array indices start at 0. So the for loop should be for( int i = 0; i < n; i++ ).
The minimum is only computed if the the elements of the array are non-negative.
I am trying to replace rows from an original 2d array to a updated 2d array. Problem is it won't store the last element during the replacement.
Here's my code:
String[][] updatedArray = {{"red","a","b","c"},{"yellow","a","b","c"}, {"purple","a","b","c"}};
String[][] originalArray = {{"red","aa","bb","cc"},{"yellow","ww","vv","zz"}, {"green","yy","uu","pp"}, {"purple","nn","mm","bb","hello"}};
for (int i = 0; i < updatedArray.length;i++ ) {
for (int j = 0; j < updatedArray[i].length; j++){
for(int x = 0; x < originalArray.length;x++){
for(int z = 0; z < originalArray[x].length;z++){
if(originalArray[x][0].equals(updatedArray[i][0])) {
updatedArray[i][j] = originalArray[x][j];
System.out.println("There's a match!!");
}else{
System.out.println("No match!");
}
}
}
}
}
System.out.println("originalArray:");
System.out.println(Arrays.deepToString(originalArray));
System.out.println("updatedArray:");
System.out.println(Arrays.deepToString(updatedArray));
For example, initially updatedArray in last row "purple" has {"purple","a","b","c"}. When it does the replacement using values from originalArray, the code above only outputs:
... [purple, nn, mm, bb]
which is wrong because it doesn't add the last element "hello". It should output:
... [purple, nn, mm, bb, hello]
I am aware the problem is in this line:
updatedArray[i][j] = originalArray[x][j];
Problem is no matter what I try to change originalArray[x][j] to originalArray[x][z] ... its screws up everything.
Any ideas on this? Still trying to get the jist of 2D arrays.
If there is a match, instead of trying to set each element in the updatedArray to the corresponding element in the original array you can just set the entire array to the original array.
String[][] updatedArray = {{"red","a","b","c"},{"yellow","a","b","c"}, {"purple","a","b","c"}};
String[][] originalArray = {{"red","aa","bb","cc"},{"yellow","ww","vv","zz"}, {"green","yy","uu","pp"}, {"purple","nn","mm","bb","hello"}};
for (int i = 0; i < updatedArray.length;i++ ) {
for (int j = 0; j < originalArray.length; j++){
if(originalArray[j][0].equals(updatedArray[i][0])) {
updatedArray[i] = originalArray[j];
System.out.println("There's a match!!");
}else{
System.out.println("No match!");
}
}
}
The issue is how you chose to iterate over the dimensions of updatedArray which are different than the dimensions of originalArray.
Let just look at the case i=2 which is the 'row' for purple:
for (int j = 0; j < updatedArray[i].length; j++){
updatedArray[i=2].length = 4
in updated:
index = 0 , 1 , 2 , 3
{"purple","a","b","c"}
in original:
index = 0 , 1 , 2 , 3 , 4
{"purple","nn","mm","bb","hello"}
Therefore since j will always be < 4 it can never be used to index originalArray[x][4] = "hello"
DANGER: this code also doesn't handle the fact that you would need to extend the purple array for updatedArray. Java may do some magic to handle this for you but I wouldn't trust it to work that way.
Suggestion:
- compare the lengths of each row and allocate extra memory where necessary before copying data from originalArray to updatedArray
- if possible just copy the whole row between original and updated.