How to check if an integer is in a given range? - java

Hoping for something more elegant than
if (i>0 && i<100)

You could add spacing ;)
if (i > 0 && i < 100)

For those using commons lang an option is to use Range:
Range<Integer> myRange = Range.between(100, 500);
if (myRange.contains(200)){
// do something
}
Also see: how to construct a apache commons 3.1 Range<Integer> object

I think
if (0 < i && i < 100)
is more elegant. Looks like maths equation.
If you are looking for something special you can try:
Math.max(0, i) == Math.min(i, 100)
at least it uses library.

ValueRange range = java.time.temporal.ValueRange.of(minValue, maxValue);
range.isValidIntValue(x);
it returns true if minValue <= x <= MaxValue - i.e. within the range
it returns false if x < minValue or x > maxValue - i.e.
out of range
Use with if condition as shown below:
int value = 10;
if (ValueRange.of(0, 100).isValidIntValue(value)) {
System.out.println("Value is with in the Range.");
} else {
System.out.println("Value is out of the Range.");
}
The below program checks, if any of the passed integer value in the hasTeen method is within the range of 13 (inclusive) to 19 (inclusive).
import java.time.temporal.ValueRange;
public class TeenNumberChecker {
public static void main(String[] args) {
System.out.println(hasTeen(9, 99, 19));
System.out.println(hasTeen(23, 15, 42));
System.out.println(hasTeen(22, 23, 34));
}
public static boolean hasTeen(int firstNumber, int secondNumber, int thirdNumber) {
ValueRange range = ValueRange.of(13, 19);
System.out.println("*********Int validation Start ***********");
System.out.println(range.isIntValue());
System.out.println(range.isValidIntValue(firstNumber));
System.out.println(range.isValidIntValue(secondNumber));
System.out.println(range.isValidIntValue(thirdNumber));
System.out.println(range.isValidValue(thirdNumber));
System.out.println("**********Int validation End**************");
if (range.isValidIntValue(firstNumber) || range.isValidIntValue(secondNumber) || range.isValidIntValue(thirdNumber)) {
return true;
} else
return false;
}
}
OUTPUT
true as 19 is part of range
true as 15 is part of range
false as all three value passed out of range

I think its already elegant way for comparing range. But, this approach cause you to write extra unit tests to satisfy all && cases.
So, you can use any of the below approach to avoid writing extra unit tests.
Using Java 8 Streams:
if(IntStream.rangeClosed(0,100).boxed().collect(Collectors.toList()).contains(i))
Using Math class:
if(Math.max(0, i) == Math.min(i, 100))
Personally I recommend the second approach because it won't end up creating an Array of the size equal to the range you want to check.

I don't see how that's not elegant, but if you repeat the expression often, then it's a good idea to put it into a method, e.g.
class MathUtil
{
public static boolean betweenExclusive(int x, int min, int max)
{
return x>min && x<max;
}
}
This is particularly true if you mix exclusive and inclusive comparisons. The method name can help avoid typos, such as using < when <= should have been used. The method can also take care of ensuring that min < max etc..

If you're looking for something more original than
if (i > 0 && i < 100)
you can try this
import static java.lang.Integer.compare;
...
if(compare(i, 0) > compare(i, 100))

This guy made a nice Range class.
Its use however will not yield nice code as it's a generic class. You'd have to type something like:
if (new Range<Integer>(0, 100).contains(i))
or (somewhat better if you implement first):
class IntRange extends Range<Integer>
....
if (new IntRange(0,100).contains(i))
Semantically both are IMHO nicer than what Java offers by default, but the memory overhead, performance degradation and more typing overall are hadly worth it. Personally, I like mdma's approach better.

if ( 0 < i && i < 100)
if ( 'a' <= c && c <= 'z' )

Google's Java Library Guava also implements Range:
import com.google.common.collect.Range;
Range<Integer> open = Range.open(1, 5);
System.out.println(open.contains(1)); // false
System.out.println(open.contains(3)); // true
System.out.println(open.contains(5)); // false
Range<Integer> closed = Range.closed(1, 5);
System.out.println(closed.contains(1)); // true
System.out.println(closed.contains(3)); // true
System.out.println(closed.contains(5)); // true
Range<Integer> openClosed = Range.openClosed(1, 5);
System.out.println(openClosed.contains(1)); // false
System.out.println(openClosed.contains(3)); // true
System.out.println(openClosed.contains(5)); // true

That's how you check is an integer is in a range. Greater than the lower bound, less than the upper bound. Trying to be clever with subtraction will likely not do what you want.

Use this code :
if (lowerBound <= val && val < upperBound)
or
if (lowerBound <= val && val <= upperBound)

if(i <= 0 || i >=100)
It will work.

if you are using Spring data you can also use the Range object from Spring.
range = new org.springframework.data.domain.Range(3, 8);
range.contains(5) // will return true.

Just my 2 cts
// Exclusive
public boolean isOrdered(int n1, int n2, int n3) {
return n1 < n2 && n2 < n3 ;
}
call it like to see it is one of 1 to 99
if (isOrdered(0,i,100))

Try:
if (i>0 && i<100) {}
it will work at least ;)

If you are confident that numbers are stored in 2's complement form:
return ((x-low) <= (high-low));
A more general and safer solution would be:
return ((x-high)*(x-low) <= 0);

Range<Long> timeRange = Range.create(model.getFrom(), model.getTo());
if(timeRange.contains(systemtime)){
Toast.makeText(context, "green!!", Toast.LENGTH_SHORT).show();
}

if (i in 0..100) {}
please try this for efficient code ;)

If you just want to test whether the value of i is in the range [0..100), and you want the boolean result, then
i >= 0 && i < 100
is fine and will give you true or false. If you are willing to throw an exception if the value is out of range, you can use the built-in checkIndex method
Objects.checkIndex(i, 100)
which will throw IndexOutOfBoundsException if out of range. Granted, it is not a general solution, and is really only prettier if your context is one in which your range check is being done for checking array bounds, but it has the advantage of not needed any third party libraries, which is nice for small programs.

Try this if strategy. Seems solid.
int num = 5;
//random values; can be changed
int a = 3;
int b = 7;
if (num >= 3 && num <= 7) {
//Your Code Here
}

Wrote this program to check the value of 3 integer parameters against a range.
I have created a separate method to check the range of the each value using if/else-if statements.
I hope this helps someone.
public class TeenNumberChecker {
public static void main(String[] args) {
boolean isTeen = hasTeen();
}
public static boolean hasTeen(int valueOne, int valueTwo, int valueThree) {
if (valueOne > 13 && valueOne < 19) {
return true;
} else if (valueTwo > 13 && valueTwo < 19) {
return true;
} else if (valueThree > 13 && valueThree < 19) {
return true;
}else {
return false;
}
}
}

Related

Turn Positive into negative?

I've got this code
public class FiboNegativV {
int negativ(int nv) {
if (nv ==0)
return 1;
if (nv ==1)
return 2;
return negativ(nv-1) + negativ(nv-2);
}
}
Now I would like to turn the final number into negative. I've tried a few things like "nv = -nv;" But I usually got stackover when I put it before the
"return negativ(nv-1) + negativ(nv-2)" and it is unreachable when it's after this line.
You don't need function for that just do it like this:
int x *= -1;
All the other answers for some reason disregard your initial intention of a Fibbonacci sequence. But I do not understand why they do not keep the context. Your method obviously tries to do a Fibbonacci sequence with recursion yielding negative numbers.
Now I would like to turn the final number into negative.
The simplest and most intuitive way of negatinv a number is to use a unary minus operator = just add a minus before the expression (so negating x to -x). We use this only on positive numbers, so that the negative ones stay negative: (note: this is a ternary operator)
(result > 0) ? -result : result;
However the big mistake is that you do NOT handle negative numbers in the recursive method in the first place! Of course you run into stack overflow, because the recursive negative numbers are going to get lower and lower.
static int negativFib(int nv)
{
//turn negative input into positive
nv = nv < 0 ? -nv : nv;
//base cases
if (nv == 0)
return 1;
if (nv == 1)
return 2;
final int result = negativFib(nv - 1) + negativFib(nv - 2);
//turn the number into negative
return result > 0 ? -result : result;
}
Alternative algorithm
An another problem which could occur is that with big numbers, the recursion comes to a stack overflow. You could prevent this by using some other algorithm, f.e. dynamic programming. With dynamic programming Fibbonacci sequence you store the previous 2 results every time and solve the problem in iterations, instead of recursion.
If you only want to convert positive into negative then
nv = (nv > 0) ? nv * -1 : nv
if you want to convert positive to negative and negative to positive then
nv = nv * -1
Below your code will look like
public class FiboNegativ
{
public FiboNegativV(){}
int negativ(int nv)
{
return (nv > 0) ? nv*-1 : nv;
}
}
Since you want only the final number to be negative, the easiest way is to work with absolute numbers, and return negative numbers, as per the following:
public class FiboNegativV {
int negativ(int nv) {
return (nv == 0) ? -1 :
(nv == 1) ? -2 :
-(Math.abs(negativ(nv-1)) + Math.abs(negativ(nv-2)));
}
}
The assumption I have made, above, is that the initial input to the function will always be positive. Your original code confirms this assumption.
-1 * (Math.abs(negativ(nv-1) + negativ(nv-2)));
Thus the result will be negative regardless of the values given.

Code optimization - BigInteger

The code works correctly until I give it a big value - it takes too much time to execute.
Can you give me some advice how to optimize it?
BigInteger type of n parameter is a must, it's a part of the task ;)
public static String oddity(BigInteger n) {
List<BigInteger> list = new ArrayList<BigInteger>();
String result = null;
for (BigInteger bi = BigInteger.valueOf(1);
bi.compareTo(n) <= 0;
bi = bi.add(BigInteger.ONE)) {
if (n.mod(bi).equals(BigInteger.ZERO))
list.add(bi);
}
if (list.size() % 2 == 0)
result = "even";
else result = "odd";
return result;
}
The purpose of this is to return 'odd' if the number of "n" divisors is odd. Otherwise return 'even'.
Thinking rather than just programming would help a lot. You don't need to find all divisors. You don't even need to count them. All you need is to find out if the count is odd.
But divisors always come in pairs: For every divisor i also n/i is a divisor.
So the count is always even, except when there's a divisor i equal to n/i. Use Guava sqrt ...
As you don't use the list except to get its final size, you could use an integer as a counter, i.e: do n++ instead of list.add(bi).
This is going to save huge amount of memory. Hence save time used to manage its allocation.
// Lambda
long counter = IntStream
.range(1, (int) Math.sqrt(n.longValue())+1)
.filter(i -> n.longValue() % i == 0 && n.longValue() / i == i)
.count();
return (counter % 2 == 0) ? "even" : "odd";
int counter = 0;
for (long i = 1; i <= Math.sqrt(n.longValue()); i++) {
if(n.longValue() % i == 0 && n.longValue()/ i == i){
counter++;
}
}
return (counter % 2 == 0) ? "even" : "odd";

Determine if a number is power of 4, logNum % logBase == 0 vs (logNum / logBase) % 1 == 0

Problem: check if a number is a power of 4.
my solution in java:
public static boolean isPowerOfFour(int num) {
return (Math.log(num) % Math.log(4) == 0);
}
But it seems off in some cases, for example when num is 64.
I found out that if I change the code a little bit, it works well.
public static boolean isPowerOfFour(int num) {
return (Math.log(num) / Math.log(4) %1 == 0);
}
I think both solutions do the same thing, check if the remaining of logNum/logBase is 0. But why the first solution doesn't work? Is it because the solution is incorrect or relative to some low level JVM stuff?
Thanks.
Building on #dasblinkenlight's answer, you can easily combine both conditions (first, a power of 2, then any power of 4 among all possible powers of 2) with a simple mask:
public static boolean isPowerOfFour(int num) {
return ((( num & ( num - 1 )) == 0 ) // check whether num is a power of 2
&& (( num & 0xaaaaaaaa ) == 0 )); // make sure it's an even power of 2
}
No loop, no conversion to float.
Checking if a number is a power of 4 is the same as checking that the number is an even power of 2.
You can check that a number x is a power of two by verifying that x & (x-1) is zero (here is the explanation of how this works)
If your number is not a power of 2, return false. Otherwise, shift the number right until you get to one, and count the number of shifts. If you shifted an odd number of times, return false; otherwise, return true:
public static boolean isPowerOfFour(int num) {
if ((num & (num-1)) != 0) {
return false;
}
int count = 0;
while (num != 1) {
num >>= 1;
count++;
}
return count % 2 == 0;
}
Demo.
Functions like Math.log return floating point numbers with a rounding error. So when num = 64 for example, Math.log (num) / Math.log (4) is not exactly 3, but a number close to 3.
public static boolean isPowerOfFour(int num) {
if (num > 0) {
while (num % 4 == 0) num /= 4;
}
return (num == 1);
}
This solution can be quite easily adapted to check whether num is a power of some other integer greater than 1.
The reason it doesn't work is because Math.log() returns a double. The answer of false is reflective of rounding errors; log(64) base e is an irrational number but Java needs to truncate it to fit it's width.

the result seems wrong

my code will be display me That is not an acceptable input. if I insert negative number. then proceed to prompt the input. But it continue to calculate. this is part of my code contains something wrong. but i did not see.
public static boolean checkOctal()
{
boolean b = true;
if (oct < 0 && oct > 99999999 )
{
b = false;
System.out.println("That is not an acceptable input.");
}
int tmp;
int tmp1 = oct;
while (tmp1 > 0)
{
tmp = tmp1 % 10;
tmp1 = tmp1 / 10;
if (tmp >= 0 && tmp < 8)
{
continue;
} else
{
b = false;
break;
}
}
return b;
}
you should write
if (oct < 0 || oct > 99999999 )
instead of
if (oct < 0 && oct > 99999999 )
|| stands for or, while && for and.
Actually, I doubt that it's displaying anything. Look at the condition:
if (oct < 0 && oct > 99999999 )
How can a number be negative and largely positive at the same time? You want an "or" condition.
Next, look at what you're doing if you did meet the condition:
{
b = false;
System.out.println("That is not an acceptable input.");
}
You're just keeping going - it will return the right result (false) but it's pointless. You know the result already, so why not just return it?
You want:
if (oct < 0 || oct > 99999999 )
{
System.out.println("That is not an acceptable input.");
return false;
}
Or, better yet, perform the validation earlier (before calling the method) - and throw an exception if the input is invalid. Currently you're giving the same result for "invalid input" as for "valid but non-octal input" which doesn't sound like a good idea to me.
Note that the approach of "return as soon as you know the value" is one I'd take for the rest of the method too - I wouldn't bother with a b variable at all. I'd change your loop to something like this:
int value = oct;
while (value > 0)
{
int digit = value % 10;
if (digit >= 8)
{
return false;
}
value = value / 10;
}
return true;
You don't need to worry about digit being negative, as you've already checked that you started off with a non-negative value.
Additionally, it seems odd that this method doesn't have oct as a parameter. That would make it more self-contained.
You should probably check your boolean logic:
if (oct < 0 && oct > 99999999 )
will never be true - no number is less than zero and larger than 999999 at the same time... The symbol || (logical "or") is what you need instead.
Cheers,

How would you compare multiple ints in 1 if statement without repeating it?

I have some coding in Java to calculate the movement in a virtual camera since the last time a variable was checked. More specifically, this code below:
float movementX, movementY, movementZ;
movementX = (int) (camX - sectorSize[1]);
movementY = (int) (camY - sectorSize[2]);
movementZ = (int) (camZ - sectorSize[3]);
/*
* If the variable is below 0
* then get the absolute value
* of the movement since the
* last camera position.
*/
if (movementX < 0) movementX *= -1;
if (movementY < 0) movementY *= -1;
if (movementZ < 0) movementZ *= -1;
if (movementX > 60 || movementY > 60 || movementZ > 60)
{
//Reset the sector size to allow for new points,
//don't store to save memory (may be changed later).
sectorSize[0] = 0;
}
If you need more of the code, let me know. The sectorSize variable stores 0-500 in its [0] value, the former camX in it's [1] value, the former camY in it's [2] value and lastly former camZ in its [3] value. The camX, camY, and camZ are handled by other code (not displayed). removed everything but the code-in-question to keep it tidy.
This code works as-is, but typing "if (a_int_value > an_other_value || etc)" each time is a bit tedious.
I would create a Movement class and encode the parameters for a "legal" movement within it.
Then you can test: movementX.isValid(). You can also keep a List or create another class to wrap the three axes and have a single isValid() method to test with.
You should consider storing sector sizes in something more descriptive than an array.
Finally, why are you casting your floats to int? What good can come from that? If you mean to strip off the decimal, there are much better ways to truncate, or floor/ceiling the value.
Put the moments into an int array.
Iterate over the array searching for all true conditions. If a true condition is encountered, mark the flag as true and break the loop. In the end, if no condition is true, your flag is false.
Something like this.
boolean ok = false;
for ( int v : momentArray ) {
if ( v > 60 ) {
ok = true;
break;
}
}
if ( ok ) {
// ok, do something...
}
Or
public static boolean checkForValues( int[] array, int min ) {
for ( int v : array ) {
if ( v > min ) {
return true;
}
}
return false;
}
// in another class...
if ( checkForValues( momentArray, 60 ) ) {
// ok, do something...
}
I'm assuming that all of conditions is the same. If they are different you can generalize the code too, but you will nedd to create a classe to store the conditions... It does not worth the work, so its preferable to code the conditions.
Another thing. You have just tree values. If you have lots of values (with the same condition) I think the iteration would be nice, but in your scenario, I think its better to code every condition because is easier to understand the code as Ghost said.
[]'s
Create a local class inside the method:
void myMethod ( )
{
class Movements
{
float movementX = (int) (camX - sectorSize[1]);
float movementY = (int) (camY - sectorSize[2]);
float movementZ = (int) (camZ - sectorSize[3]);
boolean check3Axes ( int commonValue )
{
return
movementX > commonValue
||
movementY > commonValue
||
movementZ > commonValue ;
}
void negate ( )
{
if (movementX > 0) movementX *= -1;
if (movementY > 0) movementY *= -1;
if (movementZ > 0) movementZ *= -1;
}
};
Movements m = new Movements( );
// This can be replaced with m.negate( )
if (m.movementX > 0) m.movementX *= -1;
if (m.movementY > 0) m.movementY *= -1;
if (m.movementZ > 0) m.movementZ *= -1;
if (m.check3Axes(60))
{
//do something..
}
if (m.check3Axes(120))
{
//do something else..
}
}
BTW, you may find that you can add more common methods to Movements class, such as negate().
At some point, though, it may be better to make Movement a regular class.
The inner-class looks like the best way to go. Too bad java doesn't provide anything less resource-intensive, but the ability to compare a bunch of variables with the same expression helps a lot!

Categories