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.
Related
I'm a beginner to Java and I am currently doing exercises on coding bat. For a problem (posted below), I was wondering why you would divide the length of the array by 2 to get the middle array?
Question:
"Given an array of ints of odd length, look at the first, last, and middle values in the array and return the largest. The array length will be a least 1."
arr.length will return an integer. When you divide an integer by an integer, you will get an integer that will round down. If you have a 5-element array: 1 2 3 4 5. The middle element will be 3. It will do 5/2. We know this equals 2.5. However, since we divided an int by an int, it will just return 2. Indeed, the element with an index of 2 in the array is 3, the middle element.
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.
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].
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.
How does one create a new array, containing all numbers of the array that occur at most k times in java?
For example, if the array was:
{1,4,4,3,4,3,5,2,5,1,5}
and k = 2, the new array would be:
{1,3,2}.
I assume that I would need to compare the elements within the arrays and add store the number of times it occurs as a variable. Then I would compare that variable to k and if it is smaller or equal to it, it will add it to a new arraylist. I can't really implement this tho.
Thanks
There are many ways to do this, depending on what your constraints are.
If you don't need to worry about memory constraints, you can solve this problem quite easily by using a HashMap that maps from array elements to their frequencies. The algorithm would work by scanning across the array. For each element, if that element is already in the HashMap, you update the key/value pair in the HashMap to increment the frequency of that element. Otherwise, if the element hasn't been seen, you update the frequency to be 1. Once you've finished populating the HashMap, you can then iterate across the map and copy over all elements that have frequency at most k into a new ArrayList. For example:
for(Map.Entry<T, Integer> entry: myMap.entrySet()) {
if (entry.getValue() <= k)
myArrayList.add(entry.getKey());
}
This runs in O(n) time and O(n) memory, which is quite good.
If you don't want to store everything in memory, another option would be to sort the array in O(n log n) time and O(log n) space using Arrays.sort. Once you've sorted the array, all of the copies of each value will be stored consecutively and you can more easily count their frequency. For example, after sorting the array you mentioned in your original post, you would get the array
1 1 2 3 3 4 4 4 5 5 5
From here, it should be much easier to determine how many copies of each element there are. You could do this by walking across the array, keeping track of the element you're currently looking for and how many copies there are. Whenever you see a new element, if it matches the current element, you increment the counter. If not, you reset the element you're checking to be the new element and set the counter back to one. For example, with the above array, you might start off by looking at this element:
1 1 2 3 3 4 4 4 5 5 5
^
Element: 1
Frequency: 1
Now, you look at the next element of the array. Because it's a 1, you increment the frequency count to 2:
1 1 2 3 3 4 4 4 5 5 5
^
Element: 1
Frequency: 2
When you look at the next element, you'll see that it's a 2. This means that there aren't any more 1's left. Because there are two copies of 1, you could then append 1 to the resulting array. You'd then reset the counter to 1, leaving this state:
1 1 2 3 3 4 4 4 5 5 5
^
Element: 2
Frequency: 1
The one thing to watch out for when doing this is to remember to handle the case where you visit the final array element. It's important that when you hit the end of the array, if you have at most k copies of the last element, you add the last number to the output array.
Whenever you do this, if you ever find an element that appears at most k times, you can add it to the new array. This second step runs in O(n) time and O(m) space (where m is the total number of elements in the resulting array), so the total complexity is O(n log n) time and O(m + log n) space.
Hope this helps!
You have at least two ways to do it:
Scan linearly the array, updating an hash table which stores the frequency of each encountered number (Average time: O(n), Space: O(n));
Sort the array and keeping a count of how many times you've seen the current element (which will be set to one every time the current number is different from the previous one). Time: O(n lg n), Space: O(m), where m is the number of returned element (assuming to use a O(1) space-complexity sorter, like heapsort).
The first one is time-optimal, the second one is space-optimal.