Need help finding values of arrays - java

I'm not understanding why these values continue to decrease by increments of 2.
Because the second loop ends at half of the original array length.

I ran your code just fine. The first loop creates the array and assigns it the values of i * 2. 'i' iterates between 0 and 10, creates the even numbers between 0 and 10*2.
The second loop iterates through half of the values, switching the largest value with the smallest value. It successfully reverses the array. No errors found, good job.

What is confusing here? In the first loop, you assign values 0, 2, 4,....,18 to array[0], array[1], ..., array[9]. The second loop you basically just reverse the array by swapping values of array[0] with array[9], array[1] with array[8],...etc. So 18, 16, ...0 are correct

Yes. But I'm not understanding why the values continue to decrease by
2 after 10. Since the second loop stops at half, shouldn't it start
going back up from 10 to 12 and so forth till 18? – fer0n 3 hours ago
This would be true if you removed this line:
array [array.length – 1 - i] = array[i];

The reason why I was not understanding this problem was because I wasn't fully understanding the meaning of arrays. Remember that array[#] is the position within a certain array; the # at that position will not always equal to the value at that position.
The first loop sets the positions from 0 to 9 with values multiplied by 2.
Then, the second array is where they swap the values WITHIN these positions.
For example, array[8] does not mean that the int temp equals 8. This simply means that position 8 within the array will be EQUAL to the array[1] from the very first array. Then, we set that original array position equal to the temp value, which is AT position 8.
Now, to understand why it continues to decrease its increment by 2 after 10 since the second loop has ended at position 4, one must look at this line:
array [array.length – 1 - i] = array[i];
For example, when array[9] = array[0], you place the value of 18 from temp into position 0. But you have to look at this line TWICE. The position of array at 9 will equal to the value of 0 because 0 is the value at position of array [0].

Related

Divide Array into 2 equal sum parts using only one loop, need alternative approach

Usually what we do is
1.we calculate sum of whole array from left and call it Leftsum
2.then we starts traversing array from Right end and start adding
every element into RIGHTSUM, and subracting every element from
LEFTSUM
3. untill LEFTSUM=RIGHTSUM,then we assign current value of iterator
variable I to splitpoint
4.Now array before SPLITPOINT index and from SPLITPOINT index to end have equal sum
MAIN PROBLEM------>
but this will work if array is ((3 , 5 , 10) , (3, 10 , 5)) but not on (3 , 5 , 5 , 3, 10 , 10) because we cannot find SPLITPOINT here whose left and right array sum is equal
answer of second part should also be (3,5,10) (5,3,10)
Again sum of 2 parts should be equal not length
this is an easy illustation example above
Suppose the total for the whole sequence is N. You're effectively looking for a sub-sequence that sums to N/2. (Note: if N is odd, there is no such sub-sequence!)
This is the "subset sum" problem. There's a decent Java solution for that at Finding all possible combinations of numbers to reach a given sum.

Return integer index of 1D array for 2D array of coordinates pairs

After reading 10+ threads about converting an entire array from 2D to 1D and vice versa, I'm wondering if there is a mathematical formula, requiring no iteration to return the index position of a pair of integers for a sorted 2D array.
My "grid" is always square, can be any size (it's 3x3 in this example), and I've got a sorted block of human friendly values from which I need to retrieve what I'm calling "True 1D indices" like this:
"Human-friendly" coordinates| Java 2D Indices | True 1D indices
[1,1],[1,2],[1,3], ==> [0,0],[0,1],[0,2], ==> 0 , 1 , 2
[2,1],[2,2],[2,3], ==> [1,0],[1,1],[1,2], ==> 3 , 4 , 5
[3,1],[3,2],[3,3], ==> [2,0],[2,1],[2,2], ==> 6 , 7 , 8
So I need a method for my class to give me the following results:
I enter 1,1 and get back 0,
I enter 3,2 and get back 7,
I enter 2,3 and get back 5,
etc etc...
I've played around with half a dozen equations where I try things like adding the coordinates to the previous row index squared, and I can never get the right result for every cell in the grid. Is there some special operator or Math function I'm missing?
Thanks.
let the matrix be of 3*3 ,3 rows and 3 column and we have to find the indices of (i,j) then the formula will be.
indices= 3*(i-1)+j;
Note :- here 3*3 and i,j are not it java 2d array format it is in human friendly coordinates.
Example (i,j)=(2,3)
indices=3*(2-1)+3 =6
And since your indices starts from 0 you could simply subtract one from 6 i.e. 5.
If the indices are named [index1,index2],
1DIndex = (rowNumber*index1) + index2
Where rowNumber starts at 1 for the first row, and index1 and index2 are the Java indices.

ArrayList out of [duplicate]

I get a lot of IndexOutOfBoundsException from the any Arraylist I use. Most of the times it works fine but sometimes I get this annoying error on Arraylists i use on my project.
The main cause is always either
java.util.ArrayList.throwIndexOutOfBoundsException: Invalid index 3, size is 3
or
java.util.ArrayList.throwIndexOutOfBoundsException: Invalid index 0, size is 0
Help me understand the main cause of this error as no matter how many answers I've searched they don't completely help me.
java.util.ArrayList.throwIndexOutOfBoundsException: Invalid index 3,
size is 3
It means you have ArrayList which having 3 elements where you can get each element like 0,1,2 positions. And you are trying to read 4th element which does not exists into ArrayList.
java.util.ArrayList.throwIndexOutOfBoundsException: Invalid index 0,
size is 0
It means you have a empty ArrayList, and you are trying to read 1st element.
ArrayIndexOutOfBoundsException - Examples
An array-index out of bounds exception is a Java exception thrown due to the fact that the program is trying to access an
element at a position that is outside an array limit, hence the words "Out of bounds". In other words, the program is trying to
access an element at an index that is outside the array bounds. To understand array bounds, let us consider the following diagram:
The picture above contains an array that consists of 7 elements. Each element in the array has its own index/position. In Java, an index always starts with
0 and ends with the length of the array -1. For example, the array above consists of 7 elements, therefore it's indices start from 0 and end with 6 (7-1). Attempting
to access an element with an index less than 0 or more than 6 will cause Java to throw an ArrayIndexOutOfBoundsException.
Read more about ArrayIndexOutOfBoundsException - Examples, Causes & Fixes
When your ArrayList size is 3, you can access the items at position 0 1 and 2.
If you try to access the item at position 3, it will throw an IndexOutOfBoundsException.
So when you iterate through Arraylist, your for loop should be like this
for(int i=0; i< list.size(); i++){
Object data = list.get(i);
}
Your condition must be i< list.size()
It is as simple as it gets.
java.util.ArrayList.throwIndexOutOfBoundsException: Invalid index 3,
size is 3
It says size is 3 and the index you are asking for is also 3. Array list start with 0 so the maximum index will be 2 if the size is 3.
java.util.ArrayList.throwIndexOutOfBoundsException: Invalid index 3, size is 3
this means your arraylist size = 3, but you want to access index = 3 in arraylist.
You need to know the index start at 0 in arraylist so that if your arraylist size = 3 that means you can access index from 0 to 2 like this
arraylist.get(0)
arraylist.get(1)
arraylist.get(2)
Size count starts from 1,2,3.....
Index count starts from 0,1,2....
When your arry list size is 1. you get value using 0 index. if u send index value 1. its throw exception.

2D Array containing Arrays

I'm working on a discrete math problem in Java where I'm trying to find r-permutations up to n with repetition. This means if r = 4, n = 2 we can have:
1 1 1 1
1 1 1 2
1 1 2 1
1 1 2 2, etc.
Repetition means 1112 is a unique combination, however 1211 is not because 1112 already contains 3 1's and 1 2.
Therefore I wrote code to iterate through all the permutations, and every iteration is stored in an array. There is a "Master Array" which I planned on being a 2D Array where the first dimension are all unique arrays or permutations. Therefore all I have to do is create a temp array of the new iteration and use Arrays.sort and compare the temp array to all the indexes in the master array (this works because 1211, 1112, 2111, and 1121 all sort to 1112 in ascending order).
Now, the problem I'm having is storing these arrays into the 2D array Masterkey.
I've tried:
Masterkey[count] = array;, but when I print(Masterkey[count][0]) only a single integer is being output rather than the array. (array is the newest permutation)
Masterkey[count] = Arrays.copyOf(array, array.length);, once again prints a single integer rather than the array.
Masterkey[count] = array.clone();, also prints out just an integer.
I may be overlooking something simple, but I'm just struggling to get array to be stored in Masterkey.
Masterkey[count][0] will always print a single integer because Masterkey[count] = array. so Masterkey[count][0] is the same as array[0]. However, if you assign array to Masterkey[count][0] it will print the array.

Reversing a part of an array (or any other data structure )

I want to reverse an array (or any other data structure) but because this operation is going to be done on the array for n times , im looking for the best solution possible, I have the sorted array , which is gotten in O(nlgn) time , i start looking for first element in the sorted array , inside the unsorted array ( which is equal to finding the smallest key in the unsorted array ) then I reverse the array from the beginning to the index of that value , then i do the same for the rest , find the second smallest value's index , and reverse the array again , from the second index to the end of the array and so on :
for example , consider this array :
*‫2 6 (*1*) 5 4 *3‬ // array is reversed from its 0th index to the 3rd index (0 based)
1 *5* 4 3 6 (*2*) // array is reversed from its 1st index (0 based ) to the 5th index
1 2 *6* *3* 4 5 // and ...
1 2 3 *6* *4* 5
1 2 3 4 *6* *5*
1 2 3 4 5 6
well i have to sort the array in order to have the values im looking for in the unsorted array , it'll take o(nlgn) time , and doing the algorithm above , will take o(n^2) ,any idea to make it more quick , to be done in o(nlgn) time ? so the question is reversing a sub array of the array in the least time Order , cause it's done for many times in large sized arrays. ( I can get the indices i and j ( which are the first and last index of the sub array ) in O (n) time cause i have the sorted array and i'll just look up the numbers in the unsorted array ) so im looking for the best time order for reversing an array from it's ith index to it's jth index .
thanks in advance
Here comes an O(n) solution (i think, reading your description was hard). It's a data structure wich allows 1) reversing a sub-array in O(1), 2) Getting a value from the array in O(r), where r is the number of reversings that is done, 3) find the index of an element in O(n), where n is the length of the list.
Just store our array as usual, and have a list of ReversedRange(imin, imax) elements. Reversing part of the array is as easy as inserting another element in this list.
Whenever you need to get a value from the modified array at index i, you look through all the ReversedRange for which imin <= i <= imax, and calculate the index j which corresponds to the original array index. You need to check r reversings, so it is O(r).
To get the index i of a value v, look through the original array and find the index j. Done in O(n) time. Do the same traversing of the ReversedRanges, only in the oppsite direction to calculate i. Done in O(r) time, total O(n+r) which is O(n).
Example
Consider the following list: 0 1 2 3 4 5 6 7 8 9. Now say we reverse the list form indexes 1 through 6, and then from 0 through 5. So we have:
I 0 1 2 3 4 5 6 7 8 9
| |
II 0 6 5 4 3 2 1 7 8 9
| |
III 2 3 4 5 6 0 1 7 8 9
No let us map the index i = 2 to the original array. From the graph we see that we should end up with III(2) = 4
1) since i = 2 is in [0, 5] we calculate
i <- 5 - (i - 0) = 5 - 2 = 3
2) since i = 3 is in [1, 6] we calculate
i <- 6 - (i - 1) = 6 - 2 = 4
3) there are no more ranges, we are done with result 4!
(Possibly) memory heavy...
Why don't you maintain two Collections. Traverse the original collection until you have found your reverse point. Then traverse backwards from there with an iterator or indexing if you have it (ArrayList) adding each element to a new collection. Then merge the two collections (The reversed portion and the previous untouched portion). Repeat this until finished.
Seems like a very simple answer to a complicated question so maybe I'm missing something. If you are looking for an efficient way to reverse part of an array then something like the following should work. You could easily make it generic of course.
// endIndex and startIndex are inclusive here
int half = startIndex + ((endIndex + 1) - startIndex) / 2;
int endCount = endIndex;
for (int startCount = startIndex; startCount < half; startCount++) {
int store = array[startCount];
array[startCount] = array[endCount];
array[endCount] = store;
endCount--;
}
Seems like the rest of your code would be much more complex than this. Not sure what the O() is here because it is not doing comparisons which are traditionally the measure but this is doing 1.5 x N assignments to reverse the array. I don't see any way that this can be done faster.

Categories