Java recursive methods - java

Can anyone explain to me how to get the correct answer for this question #10:
It's a sample question listed on the AP Board website for AP Computer Science

It's just a binary search. The answers are just weird because technically an index of a sorted array with no duplicates is "the number of elements less than" the value.

The correct answer (as per #KevinRaoofi's answer) is A. Your question is, however, different:
How to get the correct answer for this question?
There are different ways to do this.
For instance, you should be able to recognize binary search in this code. You take the middle element between low and high. The only "actual" return is if (arr[mid] == num) return mid; which returns index of the element which equals num. One you realize this, it is easy to see that this is exactly what the whole method is doing.
So you get an index of the element which is equal to num. The only answer which mentions index is E, but this is clearly a catch. num is not necessarily the middle element so E is not correct. Also, if in multi-choice you have N answers of more-or-less one type and one answer which is completely different, this is most probably a catch. :) Answers are usually designed to cost you time.
Now that the only answer with index is eliminated, which of A-D is correct? It seems illogical that any of them is correct as they deal with "number of elements", not index. At this point it is easy to dismiss all of the answers as incorrect. But instead, try this on a few examples:
0, 1, 2, 3, 4; num=2; result=2;
2, 4, 6, 8; num=2; result=0;
3, 5, 7, 9, 11; num=11; result=4;
Now checking answers against these results shows that A is right on every occasion. So it must be correct, but why? At this point it should be possible to realize, that index of the element in an array equals the number of elements before this index. And in ascending array these numbers are less than number at the given index (which is num). This explains why A is right on every occasion.

Related

What is the best way of checking how many elements need to be moved to sort an array? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Let's say I have an array [1, 2, 4, 5, 3]. In this array, 3, 4, and 5 are not in the position they'd be in if the array was to sorted. How can I check how many elements are not in their right position?
The fastest way I can think of is to copy the value to a temp array, sort the array and then compare which indexes have different values. That would be an O(nlogn) solution. Is there any way to do it in O(n)?
That would be an O(nlogn) solution. Is there any way to do it in O(n)?
No.
Here is an informal proof.
Suppose that there was an algorithm A that could find all elements in an array that are out of position in better than O(nlogn). Suppose also that A tells you what the correct position for each element is. This means that you can sort the array as follows:
list_of_moves = A(array);
for move in list_of_moves:
apply move
(There is a deliberate "hand wave" here, because the moves will not be simple swaps. But there are simple algorithms to do this in O(m). Consider "clock patience" for example.)
We have that A is O(n). The moving step will also be O(m) where m is the number of moves ... which is less or equal to n. So we now have a general sort algorithm that is O(n + m). That is the same complexity class as O(n).
However, there is a mathematical proof that O(nlogn) is a lower bound for general sorting algorithms. (See https://www.bowdoin.edu/~ltoma/teaching/cs231/spring14/Lectures/6-moresorting/sortLB.pdf for a presentation of the proof.)
Contradiction!
Therefore, an algorithm A with these properties that is O(n) cannot exist.
The other alternative is that the (hypothetical) algorithm A tells you (accurately) which elements are in the wrong place, but not what their correct place is.
I think that is also impossible, but I don't have a proof (right now).
Note that this is NOT the same as checking if elements are out of order. That is easy to do in O(n).
The issue is that the out of order elements can still be in the correct place. For example:
1, 4, 3, 2
The 3 is out of order, but it is in the correct place. In the fully ordered array, the 3 will be in the position it is now. The 2 and 4 will be switched.
you can just make a for loop and check if the next array index value is greater than the one before.
int x = 0;
for (int i = 0; i < array.length - 1; i++)
{
if (array[i+1] > array [i])
{
x++;
}
}
x will be the number of elements not in order

Algorithm/function that returns random number in array in O(1) and creates single permutation [duplicate]

This question already has answers here:
Random shuffling of an array
(31 answers)
Closed 7 years ago.
Intro: This is an interview question I had which I couldn't solve. A code solution will be good (in any language), but an algorithm/pseudocode is also great.
The problem: This problem is about designing an algorithm that solves the following problem:
You are given a function int getRand(int x) that gets an int x and returns an int in the range from 0 to x randomly (exclusively -> [0, k) ). Each call to getRand() is performed in O(1) time.
You are also given an array int[] arr of size k containing integers.
Write a function getRandUnique() that when called will return a random member from arr such that after k requests exactly you will have a full permutation of the members of arr (this actually means that getRandUnique() will return a different member of arr for each call).
Each call to getRandUnique() has to be performed in O(1) time.
You are allowed to use/store global variables etc...
E.g.: Assume arr = [2, 3, 5 , 1]. A call to getRandUnique() will return either 2, 3, 5, 1 in 1/4 probability. A consequent call to getRandUnique() will return on of the remaining 3 members in 1/3 probability and so on...
Attempt: I actually solved this myself (after much trial and error) and posted the solution "Q&A Style". I would love to get some other possible ideas/solutions. I will accept any solution that works as the correct answer (I don't want to accept my own)!
Question: How can this be achieved with all the above restrictions?
Edit: Now I am aware that this problem corresponds to the Fisher–Yates shuffle, even though the specifications are a little different/more strict here.
My solution is as follows:
Define index = 0.
Call and assign index = getRand(k) (remember that k is the size of arr).
Swap arr[index] with arr[k].
Now call and assign index = getRand(k-1). Now you can be certain that you won't get the index k again so you won't have to remove it.
Swap arr[index] with arr[k-1]
Continue doing this until you call the last getRand(1).
Now you have an array arr that is a random permutation of itself as requested (don't even need an additional array).

How to solve the non-negative subset sum using recursion in Java?

I am really confused by a question that says:
Given a set of non-negative integers, and a value sum, the goal is to identify all subsets whose sum of elements is equal to sum. For example, if the set of non-negative integers is {3; 34; 4; 12; 5; 2} and sum = 9, then answer is {4; 5} and {4; 2; 3}.
This question must be solved through a recursive method (one recursion function and one main string[]args function) but I have no idea on how to make it. Can someone give a hint?
Seeing you asked for a hint rather than code, I'll give you a pointer on algorithm to get you started.
Generally recursive algorithms look something like:
recursiveFunction(currentResult, context)
if currentResult satisfies given condition
process currentResult
for each possibleResult in context
recursiveFunction(possibleResult, contextWithResultRemoved)
In your case the signature of the method will be something like:
public void allSubsetsWithSum(int targetSum, Set<Integer> current, Set<Integer> remaining)
The satisfying condition test just compares the sum of current to the target.
The 'for each' would just look at each integer in remaining and move it to current before recursing.
There are efficiency shortcuts such as not processing integers from remaining that will make the sum exceed your target. But that isn't necessary to make the algorithm to work.
Hopefully that will get you started. Ask further questions if you don't understand the hints.

Array Constraint Satisfaction

Given a range of number 1 through N, where N >=3. you have to take an
array of length 2N and place each number ( from the range 1 to N)
twice. such a that the distance between two indexes of a number is
equal to the number. example
N=3
( 3, 1, 2, 1, 3, 2 )
The solution I'm thinking of is as follows:
Generate every permutation array of the range of numbers, ex: {1,2,3|, {3,2,1}, {2,1,3}, etc.
For each permutation array, run the following functions:
foreach(int number : permutationArray){
addToResultArray(number);
}
addToResultArray(int toBeAdded){
for(int i = 0; i < resultArray.length; i++){
//-1 implies the resultArray is empty at that index
if(resultArray[i]==-1 && resultArray[i+toBeAdded+1]==-1)
resultArray[i] = toBeAdded;
}
}
If the above functions do not cause an out of bounds exception, you have a valid solution.
I do not think this solution is very good. Does anyone have something better?
This can be viewed as a constrained problem: you have 2*N variables V={v1,v2,...,v2n} (representing the array indices) each variable has [1,2,..,N] possible values under the constraints:
Every value is assigned to exactly two variables.
The distance between variables with the same value equals the value itself.
An assignment is a mapping from the set of variables to their possible values. For example [v1=1,v2=3,v3=5] is an assignment for v1,v2 and v3. A given assignment is consistent if it satisfies the constraints. An example to inconsistent assignment is [v1=3,v2=1,v3=3]
An assignment is complete if its cardinality equals the variables size (i.e. 2*N). Otherwise it is a partial assignment. Clearly, our goal is to have one or more complete consistent assignment (a.k.a solution).
So the problem is basically a backtracking search problem. In particular, we have an ordering over the variables. Each time we assign a value to the current variable. If the value makes the current assignment inconsistent, we backtrack.
Your approach is actually a generate-and-test which is inefficient. Generating all solutions and counting them is hard problem in general. In most of the cases, we are looking for one solution.
Here is the interesting part: there is a much more efficient way to do this by propagating the values and detecting backtracking sooner (see constraint propagation).

Why max and min in Guava for empty arrays throw IllegalArgumentException?

I'm reading the code of Guava's Ints.max(int... array) (and similarly, Ints.min, Longs.min, etc.) They throw an IllegalArgumentException if array.length == 0 (This is Guava 15.0).
I wonder why they do not return the "identity element" in this case, instead of throwing an exception. By "identity element" I mean the element behaving like 1 for product, or 0 for sum.
That is, I would expect Ints.min() to be Integer.MAX_VALUE, Ints.max() to be Integer.MIN_VALUE, and so on.
The rationale behind this is that if you split an array in two, the min of the whole array must be the min between the mins of both sub arrays. Or, for the mathematically inclined, the sum over an empty set of real numbers is 0, the product is 1, the union of an empty collection of sets is the empty set, and so on.
Since Guava libraries tend to be carefully produced, I guess there must be an explanation for throwing an exception here. So the question is: why?
Edit: I understand that most people expect max and min of an array to be an element of the array, but this is because max/min of two elements is always one of them. On the other hand, if one regards max/min just as (commutative) binary operations, returning the identity element makes more sense. To me.
Because, IMHO, in 99.99% of the cases, when you ask the minimum element of an array, you want to get an element of this array, and not some arbitrary large value. And thus, most of the time, an empty array is a special condition, that needs a specific treatment. And not handling this special condition is thus a bug, signalled by an exception.
You said it yourself -
The rationale behind this is that if you split an array in two, the min of the whole array must be the min between the mins of both sub arrays. Or, for the mathematically inclined, the sum over an empty set of real numbers is 0, the product is 1, the union of an empty collection of sets is the empty set, and so on.
So [-1] = [-1] union [] but max([-1]) != max([-1] union []). I agree that for product or sum it makes more sense to return the respective identity, but not max/min.
I also prefer the property that max/min(S) be an element of S. Not some element having no relevance with respect to less than and greater than.
In particular if I'm working in a domain with a lot of negative numbers - say temperatures in Northern Canada - a day where my sample of temperatures is empty because the thermometer broke - it should not randomly show up as a relatively very warm day.
The minimum/maximum of array values must come from that array. If the array is empty, there there is no value to take. Returning Integer.MAX_VALUE OR Integer.MIN_VALUE here would be wrong, because those values aren't in the array. Nothing is in the array. Mathematically, the answer is the empty set, but that isn't a valid value among possible int values. There is no possible int correct answer, so the only possible correct course of action is to throw an Exception.

Categories

Resources