What exactly does array of size N mean? - java

Sorry if this may be a stupid question, but in my Java book I read this sentence:
Thus, when iterating over an array of size N, the enhanced for obtains
the elements in the array in index order, from 0 to N-1.
I am reading about the for-each style for loop, and suddenly the book is talking about an array of size N and an index order of 0 to N-1. The book does not explain what N means, and strangely enough I googled a lot but could not find the answer. Maybe I am thinking to literally or too difficult. What does size N mean? Can someone give more information about this?

The size N (or whatever it is named) is the number of items in your array or collection. Since indices are zero-based (as in other languages like C, Python, OCaml, ...), they run from 0 to N – 1.
As an example, if you have a 20-item array, N = 20 and the valid indices for this array run from 0 to 19.

An array is basically a fixed size list of elements. Here N refers to the size (or length) of the array. So it's the number of elements that it can store.
Elements in an array are obtained by using a zero-based index. That means the first element is at index 0, the second at index 1, and so on. Therefore, if the array has size N, the last element will be at index N-1 (because it starts with 0). Thus the index is in the interval [0, N-1].
Here is the official doc for arrays explaining the basics in detail.

Java provides a data structure, the array, which stores a fixed-size
sequential collection of elements of the same type. An array is used
to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type.
N is the number of items that you can store in your array.
See this link for more information:
http://www.tutorialspoint.com/java/java_arrays.htm

Hi Simon when an array has size N means that has no defined dimension that can be 1 to N.
When you don't know exactly wich is the size then in "math language" you just say N size. Be careful anyway that in Java an array can be initialized with size 0
Example:
Integer[] array = new Integer[];
Creates an empty array with length = 0.
I suggest you to have a look not only at your book but also at the official java tutorials in order to have practical code examples

N come from Natural number https://en.wikipedia.org/wiki/Natural_number but in java think of it as an int >= 0

Array size of N means the size of that array is N. It is like saying...that container holds 5 gallons or 10 gallons etc. So for a array size of 5, N=5 and for a array size of 9, N=9 and so on.
If N=9, we can store 9 elements in that array and we will access these 9 elements starting from the index 0 all the way up to index 8. Remember that there is no 9th index here because we are starting from the 0th index and when we reach index 8, we will be accessing the 9th element.
This may seem a bit tough to digest for you at this stage of your programming career....you will become comfortable after a few months, after you have seen this a few more times.

N is just a variable, it represents the amount of items could be in the array. The array could be 5 items, it could be 10 items, it could be 1000 items, it could be N items. Arrays begin from index 0, so the loop would run 0, 1, 2, 3 ... N - 3, N - 2, N - 1 times.

For example, an array with 5 elements means N = 5.

Related

In what order does a minheap sort?

I've been reading various definitions on minHeap and maxHeap. I stumbled upon statements which say:
minHeap is used to sort in descending order.
maxHeap is used to sort in ascending order.
Statements taken from the "Note" in https://www.geeksforgeeks.org/heap-sort-for-decreasing-order-using-min-heap/ .
But when I implement minHeap using PriorityQueue<Integer> in Java with default comparator, and poll() it, I get the minimum element. Why is that?
Thanks to anybody who's trying to help :).
The explanation in the blog is correct
While having a close look at the heapSort() function, it has smartly made use of min heap. The smallest element of the array gets replaced with the last element and size of heap is reduced by 1 to again heapify() it.
arr[0] -> represents the smallest element.
In every iteration, for i from n-1 to 0, the arr[0] is swapped with the arr[i] and heap is again heapified with size of 1 smaller than previous iteration.
min-heap and max-heap don't sort. You can use a min-heap or max-heap to sort, but in standard use, heaps aren't sorted. Instead, they arranged in what's called heap order. This arrangement makes it efficient to add items, and to remove the smallest (or largest) while keeping the data in the proper order.
For example, here's an illustration of a min-heap:
1
3 2
4 7 6 5
That follows the rule that no child is larger than its parent. The resulting array representation of that heap is [1,3,2,4,7,6,5]. Note that there are other valid heaps with those same numbers. For example, both of the below are valid, as well:
1 1
2 5 2 3
4 3 6 7 4 5 6 7
The corresponding array representations are [1,2,5,4,3,6,7] and [1,2,3,4,5,6,7].
Max-heap is similar, except the rule is that no child can be larger than its parent.
The Wikipedia article on binary heap explains this all very well.
Now, when you're talking about using heap sort, you build a heap and then repeatedly swap the root element with the last element in the array, reduce the count and then re-heapify. So you build the sorted array from back to front. If you use a min-heap, then the root (smallest value) will be at the end of the array.
So if you want to sort in descending order with heap sort, you use a min-heap.
The basic idea is to sort in place. Every time the algorithm polls from the heap, the heaps size shrinks by one. So one place at the end of the array is not part of the heap anymore. In this index the n-th smallest number is placed.
// One by one extract an element from heap
for (int i = n - 1; i >= 0; i--) {
// Move current root to end
swap(arr[0], arr[i]);
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
So the explanation why your algorithm using a PriorityQueue behaves so oddly is that you use a separate array for output. You could either switch to a max-heap and stick to your approach or fill the output-array in reverse. Both should produce the same behavior.

Equal elements in a Array

Today I had Interview where I was asked one problem, and I couldnt even understand.
Problem:
Given one array π‘Ž consisting of 𝑛 integers.
Get at least π‘˜ equal elements in the array π‘Ž.
While calculating, you can do below two operations
Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of π‘Ž is π‘šπ‘› then you choose such index 𝑖 that π‘Žπ‘–=π‘šπ‘› and set π‘Žπ‘–:=π‘Žπ‘–+1);
take one of the maximum elements of the array and decrease its value by one (more formally, if the maximum value of π‘Ž is π‘šπ‘₯ then you choose such index 𝑖 that π‘Žπ‘–=π‘šπ‘₯ and set π‘Žπ‘–:=π‘Žπ‘–βˆ’1).
Calculate the minimum number of moves required to obtain at least π‘˜ equal elements in the array.
Can anyone help me to undestand, what's a actual problem is about so that I could write code ?
To answer your question directly, which is "Help me understand the problem":
For example, here's your array:
{1,2,5,7,8,3}
Now, you can do only those two operations:
Find the minimum element and increase it:
{2,2,5,7,8,3} // <-- increased 1
Decrease the maximum element:
{2,2,5,7,7,3} // <-- decreased 8
And the question now is: What is the minimum number of moves to make this array contain k identical numbers?
So if k = 3 and the array is like the above, then one of the solutions would be to run operation 1 three times:
Before any moves:
{1,2,5,7,8,3}
After first move:
{2,2,5,7,8,3} // <-- `1` changed to `2`
After second move:
{3,2,5,7,8,3} // <-- `2` changed to `3`
After third move:
{3,3,5,7,8,3} // <-- `2` changed to `3`
So the resulting array would be:
{3,3,5,7,8,3}
Do you understand the problem now?
In terms of the algorithm to find k equal elements:
At any given step in the algorithm, there are some number of equal elements, say j. If j >= k, you're done. Otherwise, you need to choose some combination of the moves to increase j.
You don't have much flexibility in what you can do. You can only reduce a maximal element, or increase a minimal element.
Let's say there is a unique maximal element (i.e. when there is only one element in the array equal to the maximum element). You can increase j by (at least) 1 by reducing that until it equals the second-largest element.
Similarly, you can increase j by (at least) 1 by increasing a unique minimal element (i.e. when there is only one element in the array equal to the maximum element) until it equals the second-smallest element.
Therefore, the smallest number of moves to achieve the (at least) 1 increase is the one out of [decrease the maximal; increase the maximal] which achieve this.
For example, in the array [1, 3, 5, 6], your choices are:
Take 2 moves to increase the 1 so it equals 3: [3, 3, 5, 6]
Take 1 move to decrease the 6 so it equals 5: [1, 3, 5, 5]
In this case, you increase j by 2 most cheaply by decreasing the 6.
But after doing that, there are equal maximal elements: there are two elements equal to 5. By decreasing one of these, you decrease j by 2 (because [1, 3, 4, 5] has no equal elements); but by decreasing the maximum again, you make j the same as it was before (because [1, 3, 4, 4] again has 2 equal elements). So, you've got to do some work to "stand still" (that is, get j back to its previous value), before you can then decrease the maximum to increase j.
(Similarly for the minimal elements)
So, your algorithm can find the (greedy) minimum number of steps to make j == k by deciding whether to [decrease the maximal elements] or [increase the minimal element]. I don't know if the greedy minimum is actually the minimum, but I can't think of an obvious algorithm to find it non-greedily, other than searching all possibilities, which would have awful computational complexity, so is probably not what this interview was looking for.

How to index an array of BigIntegers by BigIntegers

I'm trying to build an array of BigIntegers, but it seems like the array needs to be indexed by integers themselves (and if true, that seems extremely stupid to me but I'm hoping I'm just misunderstanding something). What I'm trying is the essentially the following:
BigInteger totalChoiceFunctions = BigInteger.valueOf(50031545098999704);
BigInteger[][] choiceFunctions = new BigInteger[totalChoiceFunctions][36];
But this causes the error "type mismatch: cannot convert from BigInteger to int". In order to remedy this I tried:
BigInteger[][] choiceFunctions = new BigInteger[totalChoiceFunctions.intValue()][36];
however this doesn't seem to help. When I compile and run I get the runtime error of:
exception in thread 'main' java.lang.NegativeArraySizeException
Confused, I looked at the oracle documentation for the intValue() method of BigInteger and found that "if this BigInteger is too big to fit in an int, only the low-order 32 bits are returned. Note that this conversion can lose information about the overall magnitude of the BigInteger value as well as return a result with the opposite sign". I suspect this is what's going on, considering that 50031545098999704 is certainly too big for int (and why I turned towards an array of BigIntegers since I want my array to be indexed by the numbers from 1 to 50031545098999704).
If my understanding is correct, then:
BigInteger[][] chioceFunctions = new BigInteger[totalChoiceFunctions][36];
creates an array which stores BigIntegers but is still indexed by ints. How can I make an array that both stores and is indexed by BigIntegers? Is it possible? Note that the code I'm using this for might in this case be able to work if I use longs rather than ints to index, but I want it to scale to a size where I'll be forced to index by BigIntegers. Am I missing something obvious?
Arrays in java are not sparse, so your array would need about 200 000 terabyte (not including the referenced arrays/BigIntegers). So no, currently not possible. There are some plans to support long as index in arrays with maybe java 10 (certainly not java9).
I guess you actually want a sparse datastructure; a Map<BigInteger,BigInteger> or as you have a nested array Map<Tuple<BigInteger,Integer>, BigInteger> should work for you.
No, it is not possible. In java, all arrays are indexed by integers only.
In theory (but not practical), you can create such a class.
An ordinary array can't increase its size dynamically, right? But ArrayList can! How can it do that? Well, by recreating a new array with a larger size when the capacity is full.
You can kind of apply the same logic here.
An ordinary array cannot hold 50031545098999704 items. But you can create multiple arrays to hold them!
So in your class, you should have a matrix:
public class BigIntegerArray<T> {
private T[][] innerMatrix;
}
The constructor is going to accept a number as the array length, right? Using the array length, you know how many arrays you need. For example, if the array size is N where Integer.MAX_VALUE < N <= Integer.MAX_VALUE * 2, you know that you should initialize the inner matrix like this:
innerMatrix = new T[2][Integer.MAX_VALUE];
Just use some maths!
And you would want to implement a get and set method. If the index is larger than Integer.MAX_VALUE but smaller than or equal to Integer.MAX_VALUE * 2, access it like this:
innerArray[1][index - Integer.MAX_VALUE]; // not real code. I'm just illustrating the point.
You get what I mean? It's basically simple maths.
EDIT:
Maybe I didn't explain this well enough. The algorithm of creating the inner matrix is like this: (pseudocode)
if arraySize is smaller than Integer.MAX_VALUE then
create an array of size arraySize
return
initialize a variable counter to 0
while arraySize > 0
subtract Integer.MAX_VALUE from arraySize
increment counter
create an array with the array size of counter
The accessing part is similar:
if index is smaller than Integer.MAX_VALUE then
access [0][index]
return
initialize a variable counter to 0
while arraySize > 0
subtract Integer.MAX_VALUE from arraySize
increment counter
access [counter][index - Integer.MAX_VALUE * counter]
Java will only let you index by int the maximum index that you can achieve is Integer.MAX_VALUE which is 1 byte short of 2 GB which is 2147483647. Your array can not hold numbers greater than this.
You should be using a data structure which scales more than int limits, e.g. maps. Maps will behave like a 2D Array only without any limit, here you can store them as :-
Map m = new HashMap<BigInteger,BigInteger>();
The insertion and retrieval will be a little harder as compared to simple 2D array but considering the limitations of indexes using only int we have to go with another approach.

Array with large number of elements sort only largest n elements [duplicate]

This question already has answers here:
Store the largest 5000 numbers from a stream of numbers
(2 answers)
Closed 8 years ago.
I have an array containing a big number of elementsβ€”more than 2,000,000. I need to obtain the highest (or lowest) ranking 300 elements. So whenever I reach the first highest (or lowest) 300 elements of the array, return them. Currently Arrays.sort is used for the whole array, then the highest (or lowest) ranking elements are returned.
e.g.: {1,2,3,4,5,6,7,8,9} I want to obtain the highest 3 elements; I need: {9,8,7}
Any suggestions on this one?
EDIT
Best resource found so far, containing a research/comparison of different solutions:
http://www.michaelpollmeier.com/selecting-top-k-items-from-a-list-efficiently-in-java-groovy/
Source code for the article:
https://github.com/mpollmeier/Selection-Algorithms
You can use partial heapsort. Construct a minheap having 1st 300 elements.
Then as you traverse the array further, check whether the current element is greater than the root element of the heap. If it is greater, then delete the root element and add this new element.
After you finish with the entire array, your minHeap will have the largest 300 elements.
Extract the root element one by one. The elements will pop out in ascending order.
Note: The heap will always contain k(300) elements irrespective of the value of N, so heap operations shall be O(logk) in this case.
Hence order of complexity of this algorithm is O(Nlogk) where N is the size of array.
Space Complexity - O(k)
EDIT:
If you want the lowest 300 elements, then similar algorithm can be followed using a maxheap instead of minheap.
Would this work for you? This example sorts the top 4 elements in the array:
double[] arr = new double[]{1.0,4.0,2.0,8.0,3.0,6.0,7.0,5.0};
int nth = 4; //e.g. - sort the top 4 numbers
Arrays.sort(arr,arr.length-nth-1,arr.length);
System.out.println(Arrays.toString(arr));
Output:
[1.0, 4.0, 2.0, 3.0, 5.0, 6.0, 7.0, 8.0]
Use (T[], int, int, java.util.Comparator), this will sort the given array (T[]) in the range specified, only the elements from the first int arg to the second int arg. The comparator is optional.

Extracting three minimums

I want to obtain the minimum of a double array and the other two minimum values. In total I wan to obtain the 3 smaller values of the array. I am not using the class array, but I am using a double[].
Easiest way is to call
Arrays.sort()
and take the first 3 values.
Otherwise, you can simply loop through the array and keep track of the three smallest, much like you would the smallest.
double[] dlist = {17.0, 10.0, 44, 7, 4.0, 33, 24, 10, 48.0, 49.0};
Arrays.sort (dlist);
System.out.println (dlist [0] + " " + dlist [1] /*...*/);
Similarly to above, you could loop through and store the smallest one, then remove from the array. Then do it again, and again. But I think the ways mentioned above are more efficient.
Well, if you can't use the Arrays class at all, you will probably want 3 variables, one to hold each of the values you are trying to get. Just start off by setting them equal to the first 3 elements in the array (if there are at least 3, otherwise just set a few of them).
Then use a for loop to go through the rest of the elements in the array. If an element is smaller than one or more of the numbers you already found, get rid of the largest of those numbers and add this one to the list of smallest numbers instead.
1. declare 3 variables
2. set variables equal to first 3 elements in array
3. loop from index 3 (4th element) to the length of the array
a. see which of the already found numbers is bigger than the current element (if any)
b.replace the biggest of the found numbers with the new number if at least one was found
4. print out or return the numbers you found

Categories

Resources