Difference between IntStream.rangeClosed(x,y) and IntStream.range(x,y+1) - java

IntStream.range(x,y) would return a stream from x(inclusive) and y(exclusive).
IntStream.rangeClosed(x,y) would return a stream from x(inclusive) and y(inclusive).
I expected rangeClosed(x,y) to invoke range(x,y-1) or range(x,y) to invoke rangeClosed(x,y-1). But while looking at the source code for range it was like:
if (startInclusive >= endExclusive) {
return empty();
} else {
return StreamSupport.intStream(
new Streams.RangeIntSpliterator(startInclusive, endExclusive, false /*not closed*/), false);
}
The rangeClosed also had a very similar implementation rather than range(x,y+1). The only difference was that the third argument to Streams.RangeIntSpliterator was true instead of false denoting that the range is closed.
This boolean is then used to initialize int last field in Streams.RangeIntSpliterator class and the below comment is mentioned against it:
1 if the range is closed and the last element has not been traversed
Otherwise, 0 if the range is open, or is a closed range and all
elements have been traversed
Why is such an implementation necessary instead of range simply calling rangeClosed or the other way round? Is there any significant difference between calling rangeClosed(x,y) instead of range(x,y+1) ?

Even though there aren't any differences in the normal scenario, it would cause an issue when the input to the methods are min/max limits of Integer.
Assuming that rangeClosed(x,y) invokes range(x,y+1). If you are invoking rangeClosed(0, Integer.MAX_VALUE), then instead of the expected number of iterations (2147483648), the actual number of iterations would be 0, as Integer.MAX_VALUE + 1 would result in an overflow and an empty stream would be returned.
Similar overflow would cause the result to be different in case if an input is Integer.MIN_VALUE.

Related

Comparison method violates its general contract - Java Error [duplicate]

This question already has answers here:
"Comparison method violates its general contract!"
(13 answers)
Closed 1 year ago.
I have defined a Comparator using the ordering wrapper. Could you explain why does this code throw an exception, "Comparison method violates its general contract!"? I would really appreciate it if you could tell me how to fix it.
Ordering<Foo> order = new Ordering<Foo>() {
#Override
public int compare(Foo left, Foo right) {
return getCompare(orderMap, left.getItemId(), right.getItemId());
}
};
Collections.sort(Foos, order);
getCompare :
private int getCompare(Map<Long, Integer> orderMap, Long leftId, Long rightId) {
int indexLeft = orderMap.get(leftId) == null ? -1 : orderMap.get(leftId);
int indexRight = orderMap.get(leftId) == null ? -1 : orderMap.get(rightId);
if (indexLeft < 0 || indexRight < 0) {
return 1;
}
return Integer.compare(indexLeft, indexRight);
}
This is the contract:
If `a.compare(b) is X, and b.compare(c) is X, then a.compare(c) must also be X, whether X is negative, or positive, or zero.
If a.compare(b) is X, then b.compare(a) must be -X: 0 remains 0, -1 turns to +1, etc.
a.compare(a) must be 0.
That's it. Your compare method breaks this in many, many ways. For example, your second line has a bug in it(surely that'd be orderMap.get(rightId) == null, you can clean that up using getOrDefault instead), if either index is not found or less than 0, your code always returns 1, which breaks the rule (a.compare(b), where a is not in the map, returns 1, and b.compare(a) would also return 1. It needs to return a negative number instead).
You're going to have to come up with a rule for what happens if one of these is not in the map. If your code is written with the assumption it can't happen, well, it is - throw an exception when your assumption doesn't hold so you can investigate why your assumption (that all provided left/rightIds are always in the map and always non-negative). As written, your code straight up asplodes in a nasty way if that happens - that's what exceptions are for. Explode in an easily debuggable way.
If that was the intent, you're going to have to make up some rules. For example: If a is in the map but b is not, then a is always higher than b. That means if (indexLeft < 0 && indexRight >= 0) return -1 and also if (indexLeft >= 0 && indexRight < 0) return +1;, in order to stick to the rules. That leaves the question: What if neither is in. You can either choose that there is then no way to order them (Return 0), but do know that means you can't put more than once such item in a TreeMap or TreeSet - but sorting a list, that's fine. Individually not-comparables are allowed, and they'll end up clumped together in an arbitrary order. That doesn't break the rules.

How to code these conditional statements in more elegant & scalable manner

In my software, I need to decide the version of a feature based on 2 parameters. Eg.
Render version 1 -> if (param1 && param2) == true;
Render version 2 -> if (!param1 && !param2) == true;
Render version 3 -> if only param1 == true;
Render version 4 -> if only param2 == true;
So, to meet this requirement, I wrote a code which looks like this -
if(param1 && param2) //both are true {
version = 1;
}
else if(!param1 && !param2) //both are false {
version = 2;
}
else if(!param2) //Means param1 is true {
version = 3;
}
else { //Means param2 is true
version = 4;
}
There are definitely multiple ways to code this but I finalised this approach after trying out different approaches because this is the most readable code I could come up with.
But this piece of code is definitely not scalable because -
Let say tomorrow we want to introduce new param called param3. Then
the no. of checks will increase because of multiple possible
combinations.
For this software, I am pretty much sure that we
will have to accommodate new parameters in future.
Can there be any scalable & readable way to code these requirements?
EDIT:
For a scalable solution define the versions for each parameter combination through a Map:
Map<List<Boolean>, Integer> paramsToVersion = Map.of(
List.of(true, true), 1,
List.of(false, false), 2,
List.of(true, false), 3,
List.of(false, true), 4);
Now finding the right version is a simple map lookup:
version = paramsToVersion.get(List.of(param1, param2));
The way I initialized the map works since Java 9. In older Java versions it’s a little more wordy, but probably still worth doing. Even in Java 9 you need to use Map.ofEntries if you have 4 or more parameters (for 16 combinations), which is a little more wordy too.
Original answer:
My taste would be for nested if/else statements and only testing each parameter once:
if (param1) {
if (param2) {
version = 1;
} else {
version = 3;
}
} else {
if (param2) {
version = 4;
} else {
version = 2;
}
}
But it scales poorly to many parameters.
If you have to enumerate all the possible combinations of Booleans, it's often simplest to convert them into a number:
// param1: F T F T
// param2; F F T T
static final int[] VERSIONS = new int[]{2, 3, 4, 1};
...
version = VERSIONS[(param1 ? 1:0) + (param2 ? 2:0)];
I doubt that there is a way that would be more compact, readable and scalable at the same time.
You express the conditions as minimized expressions, which are compact and may have meaning (in particular, the irrelevant variables don't clutter them). But there is no systematism that you could exploit.
A quite systematic alternative could be truth tables, i.e. the explicit expansion of all combinations and the associated truth value (or version number), which can be very efficient in terms of running-time. But these have a size exponential in the number of variables and are not especially readable.
I am afraid there is no free lunch. Your current solution is excellent.
If you are after efficiency (i.e. avoiding the need to evaluate all expressions sequentially), then you can think of the truth table approach, but in the following way:
declare an array of version numbers, with 2^n entries;
use the code just like you wrote to initialize all table entries; to achieve that, enumerate all integers in [0, 2^n) and use their binary representation;
now for a query, form an integer index from the n input booleans and lookup the array.
Using the answer by Olevv, the table would be [2, 4, 3, 1]. A lookup would be like (false, true) => T[01b] = 4.
What matters is that the original set of expressions is still there in the code, for human reading. You can use it in an initialization function that will fill the array at run-time, and you can also use it to hard-code the table (and leave the code in comments; even better, leave the code that generates the hard-coded table).
Your combinations of parameters is nothing more than a binary number (like 01100) where the 0 indicates a false and the 1 a true.
So your version can be easily calculated by using all the combinations of ones and zeroes. Possible combinations with 2 input parameters are:
11 -> both are true
10 -> first is true, second is false
01 -> first is false, second is true
00 -> both are false
So with this knowledge I've come up with a quite scalable solution using a "bit mask" (nothing more than a number) and "bit operations":
public static int getVersion(boolean... params) {
int length = params.length;
int mask = (1 << length) - 1;
for(int i = 0; i < length; i++) {
if(!params[i]) {
mask &= ~(1 << length - i - 1);
}
}
return mask + 1;
}
The most interesting line is probably this:
mask &= ~(1 << length - i - 1);
It does many things at once, I split it up. The part length - i - 1 calculates the position of the "bit" inside the bit mask from the right (0 based, like in arrays).
The next part: 1 << (length - i - 1) shifts the number 1 the amount of positions to the left. So lets say we have a position of 3, then the result of the operation 1 << 2 (2 is the third position) would be a binary number of the value 100.
The ~ sign is a binary inverse, so all the bits are inverted, all 0 are turned to 1 and all 1 are turned to 0. With the previous example the inverse of 100 would be 011.
The last part: mask &= n is the same as mask = mask & n where n is the previously computed value 011. This is nothing more than a binary AND, so all the same bits which are in mask and in n are kept, where as all others are discarded.
All in all, does this single line nothing more than remove the "bit" at a given position of the mask if the input parameter is false.
If the version numbers are not sequential from 1 to 4 then a version lookup table, like this one may help you.
The whole code would need just a single adjustment in the last line:
return VERSIONS[mask];
Where your VERSIONS array consists of all the versions in order, but reversed. (index 0 of VERSIONS is where both parameters are false)
I would have just gone with:
if (param1) {
if (param2) {
} else {
}
} else {
if (param2) {
} else {
}
}
Kind of repetitive, but each condition is evaluated only once, and you can easily find the code that executes for any particular combination. Adding a 3rd parameter will, of course, double the code. But if there are any invalid combinations, you can leave those out which shortens the code. Or, if you want to throw an exception for them, it becomes fairly easy to see which combination you have missed. When the IF's become too long, you can bring the actual code out in methods:
if (param1) {
if (param2) {
method_12();
} else {
method_1();
}
} else {
if (param2) {
method_2();
} else {
method_none();
}
}
Thus your whole switching logic takes up a function of itself and the actual code for any combination is in another method. When you need to work with the code for a particular combination, you just look up the appropriate method. The big IF maze is then rarely looked at, and when it is, it contains only the IFs themselves and nothing else potentially distracting.

Recursion gives unexpected/wrong output?

So I was doing a recursion challenge on codingbat and came across the "bunny ears" problem where we have a number of bunnies and each bunny has two big floppy ears. We want to compute the total number of ears across all the bunnies recursively (without loops or multiplication).
The solution apparently is quite simple:
public int bunnyEars(int bunnies)
{
if(bunnies == 0)
return 0;
return 2+bunnyEars(bunnies-1);
}
But I am not able to understand. If we pass 2 in the bunnyEars(2) method the
recursive part bunnyEars(bunnies-1); should have 1 left in the bracket after subtraction and thus 2+(1); which should be equal to 3 and not 4.
But the output comes as 4. So how does recursion actually work in this code?
It is not 2+(1), it is 2+numberOfEarsOfBunnies(1) == 2+2.
I renamed the function a little to make it more obvious.
Or even more into detail:
numberOfEarsOfBunnies(2)==
2+numberOfEarsOfBunnies(1)==
2+(2+numberOfEarsOfBunnies(0))==
2+(2+0)==
2+2==
4
if we pass 2 in the bunnyEars(2) method the recursive part bunnyEars(bunnies-1); should have 1 left in the bracket after subtraction and thus 2+(1); should be equal to 3 and not 4.
It seems you're misreading the expression. The line of code in question says
return 2+bunnyEars(bunnies-1);
Now you call bunnyEars(2), so bunnies == 2; and then you reach this line of code.
return 2+bunnyEars(bunnies-1);
resolves to
return 2+bunnyEars(2-1);
or
return 2+bunnyEars(1);
So a second instance of the bunnyEars() function starts running, with bunnies == 1. It reaches that same line of code, and this time
return 2+bunnyEars(bunnies-1);
is
return 2+bunnyEars(1-1);
or
return 2+bunnyEars(0);
So a third instance of bunnyEars() gets running, with bunnies == 0; but this matches your base case, so you just return 0 ; this time we don't recurse. So back up a level we find that
return 2+bunnyEars(0);
is
return 2+0; // because bunnyEars(0) returned 0
so that instance returns 2. And that means
return 2+bunnyEars(1);
becomes
return 2+2; // because bunnyEars(1) returned 2
And of course 2+2 is 4, the correct answer.
It seems as though you applied the -1 to the return value of the recursive bunnyEars() call, but the code says to apply it to the parameter you're sending in, not to the return value.

Java Recursion - Did I do this right? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
My job is to write a recursive version to this method. From what I understand Recursion is starting with a base call (if something then return) followed by an else which unwinds back to the original base. Like starting with a deck, adding on to the deck then removing cards from the deck until you are back to the original deck.
With that in mind here it is.
public static long fact(int n)
{
long result = 1;
while(n > 0)
{
result = result * n;
n = n - 1;
}
return result;
}
//my recursive version:
public static void recFact(int n)
{
if(n==0)
{
return n; // ir 0 it really doesn't matter right?
}
else
{
return recFact(n-1);
}
}
This is just an example test problem for an exam I have coming up, just want to make sure I have a handle on recursion. Did I do this right? If not what am I missing? please no answers in questions, just tell me what I did wrong and maybe some advice on better ways to understand it.
Thanks.
No, this recursive solution is not correct.
For every positive n, you're just return rectFact(n-1), which will recourse until you reach 0, at which point it will return. In other words, your function will always return 0. You're missing the part where you multiply the current n with rectFact(n-1). Additionally, note that 0! is 1, not 0:
public static int recFact(int n)
{
if(n==0)
{
return 1;
}
else
{
return n * recFact(n-1);
}
}
And finally, since the if clause returns, the else is somewhat redundant. This doesn't affect the method's correctness, of course, but IMHO the code looks cleaner without it:
public static int recFact(int n)
{
if(n==0)
{
return 1;
}
return n * recFact(n-1);
}
Your recursive version does no multiplication, and it will return zero for any input. So no, you didn't do it right.
But, the recursive version DOES recurse, so you have that going for you! To understand what's going wrong, walk through a very simple case.
Client calls recFact(3)
This will return to client recFact(2)
Which will return to above recFact(1)
Which will return to above recFact(0)
Which will return to above 0.
There are two major things going wrong:
Your base case is wrong (zero is too low)
You're not doing any multiplication
Good attitude about not wanting the solution handed to you! Hopefully these pointers wil help you figure it out.
EDIT: Apparently I misunderstood your grammar and you did want the solution.
Any recursive function needs three things:
The terminating condition: This tells the function when to stop calling itself. This is very important to avoid infinite recursion and avoid stack overflow exceptions.
The actual processing: You need to run the actual processing within each function. In your non recursive case, this was result = result * n. This is missing from your recursive version!
A collector/agggregator variable: You need some way to store the partial result of the recursive calls below you. So you need some way to return the result of recFact so that you can include it in processing higher up in the call chain. Note that you say return recFact(n - 1) but in the definition recFact returns void. That should probably be an int.
Based from your example you are missing the return type of your recFact which is int
Also recFact will always return 0 because you are not multiplying n each time to the recursion call of the method.
There are two ways to write recursive routines. One is the "standard" way that we all are taught. This is one entry point that must first check to see if the recursive chain is at an end (the escape clause). If so, it returns the "end of chain" value and ends the recursion. If not at the end, it performs whatever calculation it needs to get a partial value according to the level and then calls itself passing a value the next increment closer to the end of the chain.
private final int InitialValue = 15;
System.out.println( "Fact(" + InitialValue + ") = " + recFact( InitialValue ) );
public int recFact( int val ){
if( val < 2 ){
return 1;
}
else{
return recFact( val - 1 ) * val; // recursive call
}
}
//Output: "Fact(15) = 2004310016"
In regular recursion, a partial answer is maintained at each level which is used to supplement the answer from the next level. In the code above, the partial answer is val. When first called, this value is 15. It takes this value and multiplies it by the answer from Fact(14) to supply the complete answer to Fact(15). Fact(14) got its answer by multiplying 14 by the answer it got from Fact(13) and so on.
There is another type of recursion called tail recursion. This differs in that partial answers are passed to the next level instead of maintained at each level. This sounds complicated but in actuality, make the recursion process much simpler. Another difference is that there are two routines, one is non recursive and sets up the recursive routine. This is to maintain the standard API to users who only want to see (and should only have to see)
answer = routine( parameter );
The non-recursive routines provides this. It is also a convenient place to put one-time code such as error checking. Notice in the standard routine above, if the user passed in -15 instead of 15, the routine could bomb out. That means that in production code, such a test must be made. But this test will be performed every time the routine is entered which means the test will be made needlessly for all but the very first time. Also, as this must return an integer value, it cannot handle an initial value greater than 19 as that will result in a value that will overflow the 32-bit integer container.
public static final int MaxFactorialSeq = 20;
private final int InitialValue = 15;
System.out.println( "Fact(" + InitialValue + ") = " + recFact( InitialValue ) );
public int recFact( int value ){
if( value < 0 || value > MaxFactorialSeq ){
throw new IllegalArgumentException(
"Factorial sequence value " + value + " is out of range." );
}
return recFact( value, 1 ); // initial invocation
}
private int recFact( int val, int acc ){
if( val < 2 ){
return acc;
}
else{
return recFact( val - 1, acc * val ); // recursive call
}
}
//Output: "Fact(15) = 2004310016"
Notice the public entry point contains range checking code. This is executed only once and the recursive routine does not have to make this check. It then calls the recursive version with an initial "seed" of 1.
The recursive routine, as before, checks to see if it is at the end of the chain. If so, it returns, not 1 as before, but the accumulator which at this point has the complete answer. The call chain then just rewinds back to the initial entry point in the non-recursive routine. There are no further calculations to be made as the answer is calculated on the way down rather than on the way up.
If you walk though it, the answer with standard recursion was reached by the sequence 15*14*13*...*2*1. With tail recursion, the answer was reached by the sequence 1*15*14*...*3*2. The final answer is, of course, the same. However, in my test with an initial value of 15, the standard recursion method took an average of 0.044 msecs and the tail recursion method took an average of 0.030 msecs. However, almost all that time difference is accounted for by the fact that I have the bounds checking in my standard recursion routine. Without it, the timing is much closer (0.036 to 0.030) but, of course, then you don't have error checking.
Not all recursive routines can use tail recursion. But then, not all recursive routines should be. It is a truism that any recursive function can be written using a loop. And generally should be. But a Factorial function like the ones above can never exceed 19 levels so they can be added to the lucky few.
The problem with recursion is that to understand recursion you must first understand recursion.
A recursive function is a function which calls itself, or calls a function which ultimately calls the first function again.
You have the recursion part right, since your function calls itself, and you have an "escape" clause so you don't get infinite recursion (a reason for the function not to call itself).
What you are lacking from your example though is the actual operation you are performing.
Also, instead of passing a counter, you need to pass your counter and the value you are multiplying, and then you need to return said multiplied value.
public static long recFact(int n, long val)
{
if(n==1)
{
return val;
}
else
{
return recFact(n-1, val) * n;
}
}

Calculate the power of 2, java

I want to calculate the power of 2 using recursion. Here is my code:
class Aufg1{
public static void main(String args[]){
int erg = zweiHochPositiv(10);
}
public static int zweiHochPositiv(int exponent){
if(exponent > 0)
return (2*zweiHochPositiv(exponent--));
else
return 1;
}
}
I get a lot of errors at
return (2*zweiHochPositiv(exponent--));
but I have no idea what may be wrong.
Replace
return (2*zweiHochPositiv(exponent--));
with
return (2*zweiHochPositiv(exponent - 1));
exponent-- evaluates to the value of the exponent variable and then decrements it. So when you call zweiHochPositiv(1), the method will call zweiHochPositiv(1) again.
As a result, this method, when called with a value > 0, will recurse indefinitely and ultimately overflow the stack.
You need to use prefix version of --.
This should work:
return (2*zweiHochPositiv(--exponent));
Explanation: exponent-- will never actually lower exponent's value, so you're calling your recursive function every time with the same value, and that will blow your stack.
--exponent will lower it's value by one, so you should get desired behaviour.
I think an efficient way of doing it would be to use the binary representation property of a "power of 2" - its just a bit shift of 1, "exponent" number of times.
Hence, 2^2 = 1 << 2 = (in binary) ....0000 0100 = 4
return (2*zweiHochPositiv(--exponent));

Categories

Resources