Extracting three minimums - java

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

Related

How to find the highest pair from 2 arrays and that isnt above a specified budget

lets say you have two lists of ints: [1, 2, 8] and [3, 6, 7]. If the budget is 6, the int returned has to be 5 (2+3). I am struggling to find a solution faster than n^2.
The second part of the question is "how would you change your function if the number of lists is not fixed?" as in, there are multiple lists with the lists being stored in a 2d array. Any guidance or help would be appreciated.
I think my first approach would be to use for statements and add the elements to each of the next array, then take whatever is close to the budget but not exceeding it. I am new to java and I don't get your solution though, so I don't know if this would help.
For the second part of your question, are you referring to the indefinite length of your array? If so, you can use the ArrayList for that.
I will provide an answer for the case of 2 sequences. You will need to ask a separate question for the extended case. I am assuming the entries are natural numbers (i.e. no negatives).
Store your values in a NavigableSet. The implementations of this interface (e.g. TreeSet) allow you to efficiently find (for example) the largest value less than an amount.
So if you have each of your 2 sets in a NavigableSet then you could use:
set1.headSet(total).stream()
.map(v1 -> Optional.ofNullable(set2.floor(total - v1)).map(v2 -> v1 + v2)
.flatMap(Optional::stream)
.max(Integer::compareTo);
Essentially this streams all elements of the first set that are less than the total and then finds the largest element of the second set that's less than total - element (if any), adds them and finds the largest. it returns an Optional which is empty if there is no such element.
You wouldn't necessarily need the first set to be a NavigableSet - you could use any sorted structure and then use Stream.takeWhile to only look at elements smaller than the target.
This should be O(n * log n) once the sets are constructed. You could perhaps do even better by navigating the second set rather than using floor.
The best way to approach the problem if there are multiple lists, would be to use a hash table to store the pair or sequence of values that sum to the number you want (the budget).
You would simply print out the hash map key and values (key being an integer, values: a list of integers) that sum to the number.
Time complexity O(N) where N is the size of the largest list, Space Complexity of O(N).

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.

Obtaining the absolute difference between consecutive elements in an array, and returning which difference occurred the most

So if there's an array like [2, 3, 5, 7, 11], the differences would be 1, 2, 2, 4, therefore you'd return 2.
Brute force would be to just iterate over the initial structure, store each calculated difference in a new structure, and count the most number of occurrences of an element in that new structure.
I'm wondering if there's a different, better way to do this, or if that solution would be considered efficient?
That solution will be efficient, if implemented "properly". If you're using a package with a vectorized array type, then use the shift operation to get the vector of differences. That's O(N) with or without the vectorization.
A second linear pass will find the mode of the array, yielding your final answer. Keep a simple array to count how many times each value appears:
for item in diff_array:
mode_ct[item] += 1
Then find the max of mode_ct; return its index.

What exactly does array of size N mean?

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.

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.

Categories

Resources