Converting this line of code to a for loop - java

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);

Related

for loop math with array in java

I'm trying to practice using Arrays methods in java. I used the following code to make an Java array:
int numArr[] = new int[10];
for(int i = 0; i< numArr.length;++i)
{
numArr[(numArr.length)-i-1] = (i+1)*2;
System.out.println("numArr[i]" + numArr[i]);
}
My intention was to use this to make the list 20,18,...,4,2. Then, I wanted to use the Arrays sort method to see if it worked properly.
The odd result that I can't understand is that above code prints:
numArr[i] = 0;
numArr[i] = 0;
numArr[i] = 0;
numArr[i] = 0;
numArr[i] = 0;
numArr[i] = 10;
numArr[i] = 8;
numArr[i] = 6;
numArr[i] = 4;
numArr[i] = 2;
I understand the simple mistake with printing the i each time but I don't understand why the initial results are all the 0. I thought maybe it just failed and they were still just initialized to the 0 default. But then I realized that after later in the code after using Arrays.sort(), the list prints correctly for all of the indexes 2,4,...,18,20.
What mistake am I making on the pre-sorted array print?
Your mistake is in how you are indexing into the array in the loop. You are assigning to array element (numArr.length)-i-1 but printing array element i. Try printing array element (numArr.length)-i-1 inside the loop to see the value you just assigned.
Let's say i=0, or the first loop.
numArr[(numArr.length)-i-1] = (i+1)*2;
Run that through, you get
numArr[9] = 2;
Yet, you print numArr[0], which is not yet assigned.
You'll start seeing values once you reach the midpoint of the array
If you are still confused, write out your algorithm on paper
You are trying to print the results even before they are populated in the array.
Here you are populating from behind but trying to print from front(Which are not yet given any value)
Wait for the array to get populated and loop through the array to get the proper result
Doing this should solve your problem,
for(int i = 0; i< numArr.length;++i)
{
numArr[(numArr.length)-i-1] = (i+1)*2;
}
for(int i = numArr.length-1; i>-1;i--)
{
System.out.println(numArr[i]);
}
You are trying to print indexes which has their default value (0) in it. Instead, try printing the indexes which you've already assigned a value into
for(int i = 0; i< numArr.length;++i)
{
numArr[i] = (i+1)*2;
System.out.println("numArr[i]" + numArr[i]);
}
or
for(int i = 0; i< numArr.length;++i)
{
numArr[(numArr.length)-i-1] = (i+1)*2;
System.out.println("numArr[i]" + numArr[(numArr.length)-i-1]);
}
As #Vinay pointed out when printing you are using i as subscript for array elements that didn't get populated yet. If you want to print array while populated you have to use the same index
int numArr[] = new int[10];
for(int i = 0; i< numArr.length;++i)
{
numArr[(numArr.length)-i-1] = (i+1)*2;
System.out.println("numArr[(numArr.length)-i-1]);
}
The easiest way is populate the array and then print the result with another loop:
Test:
public class Test
{
public static void main ( String [ ] args )
{
int numArr[] = new int[10];
for(int i = 0; i< numArr.length;++i)
{
numArr[(numArr.length)-i-1] = (i+1)*2;
}
for(int i = 0; i < numArr.length; i++)
{
System.out.println("numArr["+i+"]" + numArr[i]);
}
}
}
Output:
numArr[0]20
numArr[1]18
numArr[2]16
numArr[3]14
numArr[4]12
numArr[5]10
numArr[6]8
numArr[7]6
numArr[8]4
numArr[9]2
int numArr[] = new int[10];
for(int i = numArr.length-1; i >= 0; i--)
{
numArr[i] = (i+1)*2;
System.out.println("numArr["+i+"]" + numArr[i]);
}
Output:
numArr[9]20
numArr[8]18
numArr[7]16
numArr[6]14
numArr[5]12
numArr[4]10
numArr[3]8
numArr[2]6
numArr[1]4
numArr[0]2
Is this what you wanted to look like?
[Vote up if helped]

Java Matrix how to assign int 1 or 0 to a 2D array? [duplicate]

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.)

Find the maximum of the length of 2 arrays

I am passing 2 arrays to the controller with different lengths, I want to execute a for loop and length of that will be the max of the length of 2 arrays.
I am not getting how to execute that. I tried Math.max but its giving me error as cannot assign a value to the final variable length.
String[] x =0;
x.length = Math.max(y.length,z.length);
for(int i=0; i < x.length; i++)
The no of elements in x and y are not fixed. it changes what we are passing from the front end.
Initialize the new array with the desired length:
String[] x = new String[Math.max(y.length,z.length)];
In case you don't need to create an array, just use the result of Math.max as conditional to stop your loop:
for (int i = 0; i < Math.max(y.length,z.length); i++) {
//...
}
Just bring your Math.max() operation into the array's initialization.
String[] x = new String[Math.max(y.length, z.length)];
Here's an expansion for clarity:
int xLength = Math.max(y.length, z.length);
String[] x = new String[xLength];
Edit: Unless, OP, you're not interested in creating another array...
I want to execute a for loop and length of that will be the max of the length of 2 arrays
Just bring your Math.max() operation into your for loop:
for(int i=0; i < Math.max(y.length, z.length); i++){
//code here
}
Set a variable to the maximum length of the arrays, create a new array with that length and then loop until that point.
int maxLen = Math.max(y.length, x.length);
String[] array = new String[maxLen];
for(int i = 0; i < maxLen; i++){
// Loop code here
}
int max_length = Math.max(y.length,z.length);
for(int i=0; i < max_length ; i++){
//...
}
you can use that max_length to create a new String[] if you are trying to create an array with total length of y and z arrays, like
String[] newArray = new String[max_length];

Java integer array, I cant do simple maths it seems

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--)

How to increment the size of an array within a loop

I have this bubblesort code that i'm performing a runtime analysis on recording the time it takes to sort the array. I was wondering if there is any way i could increment the size of the array using a loop? Because at the moment i am incrementing it 100 at a time manually and i need to reach an array size of 5000.
public class BubbleSortworking{
public static void main (String[] args) {
Random rand = new Random();
int myArray[] = new int[100]; //How to increment this using a loop
int count, count2;
count2 = 2; //amount of times to run the loop
//repeats the bubble sort, while also producing new arrays each time
for (count = 0; count < count2; count++){
for (int i = 0; i < myArray.length; i++){
myArray[i] = rand.nextInt(100) + 1; //produce numbers between 1 - ?
//System.out.print(myArray[i] + ", "); //displays unsorted array
}
bubble(myArray);
// uncomment below 2 lines to prove each new sorted array cycle is unique
//for (int i = 0; i < myArray.length; i++)
// System.out.print(myArray[i] + ", ");
}
}
public static void bubble(int myArray[]){
int temp;
long start = System.nanoTime();
//System.out.println("start " + start);
//for (count = 0; count < count2; count++){
for (int i=0; i < myArray.length - 1; i++) {
for(int j=myArray.length - 1; j > i; j--) {
if (myArray[j] < myArray[j-1]){
temp = myArray[j];
myArray[j] = myArray[j-1];
myArray[j-1] = temp;
}
}
}
long end = System.nanoTime();
System.out.println(end - start);
//System.out.println("elapsed time " + (end - start));
}
}
No you can't change the size of an array once created. You either have to allocate it bigger than you think you'll need or accept the overhead of having to reallocate it needs to grow in size. When it does you'll have to allocate a new one and copy the data from the old to the new.
You either need to use an ArrayList, which will do this for you but with extra overheads.
Or, you can allocate the array as size 5000 before you start, and record up to how many elements you have used so far in a variable (rather than relying on array.length)
Or, you can resize the array by making a new array which is bigger and copying all the elements to it (System.arrayCopy(..)), as well as putting the new ones in.
The answer by rizon is correct, you cannot change the size of an array. BTW, nowhere are you re-creating the array, nor do I see where you are processing 5000 elements. If you are concerned about processing time, you would not want to recreate/resize an array, as that would be very inefficient. You would want a different solution.
This may help you
int[] intA = new int[100];
int sizeToIncrement = 100;
for(int i=0;i<5000;i++) {
if(i== intA.length ) {
intA = Arrays.copyOf(intA, intA.length + sizeToIncrement);
}
intA[i] = i;
}

Categories