Implementing array with min-value ints - java

I currently have a nxn array of ints. I plan to initialize all the cells within the array with infinity and later change it if a value being compared to the cell is lower than the value inside the cell. Here is the pseudo-code of what I came up with so far, using -1 to represent infinity. What do you think? Is this the most efficient way, any bugs?
if(table[i][j] == -1 || (table[i][j] != -1 && table[i][j] > value)
then table[i][j] = value

I would instead start with Integer.MAX_VALUE. This way, the code could be simpler :
if(table[i][j] > value) {
table[i][j]=value;
}
Notice that, were your array to contain doubles, you could even go as far as using Double.POSITIVE_INFINITY.

If you are sure that the value -1 can be treated as a "reserved" value, you should be fine with such approach.
You could also consider encapsulating the datatype in some PossiblyInfinitInteger which has a boolean of whether or not it is set to infinity. Perhaps an overkill, I don't know.

if(table [i][j] == -1 || table[i][j] > value) then ... does the same. I'm not sure, but the compiler may take care of this.
If -1 is reserved, and the values cannot be less than 0, your approach is correct, just compare table[i][j] < value and not visa versa.
If using -1 as a reserved value is a problem, use Integer.MAX_VALUE:
if(table[i][j] == Integer.MAX_VALUE) then table[i][j] = value;

Related

Binary search implementation in Java

if(this.passenger.validatePassengerDetails() && checkEngine() && this.capacity <= 200) {
if(Arrays.binarySearch(airlineClassAir, "flightClass") >=0 && (destination.equals("tx") || destination.equals("ca"))) {
int index = Arrays.binarySearch(airlineClassAir, "flightClass");
int amount = airlineClassPriceAir[index];
double totalAmount = amount + amount* (18/100);
I am trying to understand how the binary search is being implemented here? Can someone explain if(Arrays.binarySearch(airlineClassAir, "flightless") >=0 is trying to do here?
As documented on Arrays.binarySearch(Object[], Object) (emphasis mine):
Returns:
index of the search key, if it is contained in the array; otherwise,
(-(insertion point) - 1). The insertion point is
defined as the point at which the key would be inserted into the
array: the index of the first element greater than the key, or
a.length if all elements in the array are less than the specified
key. Note that this guarantees that the return value will be >= 0 if
and only if the key is found.
In other words, you compare with >= 0 to check if the value exists in the array. Be aware though of the requirement that the array must be sorted (an earlier version of your answer showed it wasn't sorted), otherwise the behaviour is undefined: it might find the item, or it might return a negative value even if the value exists.
To explicitly answer the question, the expression Arrays.binarySearch(airlineClassAir, "flightless") >=0 will be true if airlineClassAir contains the string "flightless", and false otherwise (assuming it is sorted, otherwise it might return false even if the value is in the array).
Personally, if your requirement is to check for existence and there are no other uses of that array, I would use a Set<String> and use its contains method instead, as that expresses intent more clearly.

Fibonacci Memoized/Dynamic Programming in Java

So this is some code to calculate the Fibonacci sequence with memoization. What confuses me is when we check if memo[i]==0. I understand that Java arrays are initialized to zero and thus if memo[i] == 0 this may mean that the computation for memo[i] has not yet occured. However, one of the return values for this fibonacci function is 0. So doesn't this mean that let's say if fib(3)=0 (I know it doesn't but just for the sake of arguement) then everytime we have fib(3) we would wind up recomputing fib(3) because the check is if(memo[i] == 0) right? And if that is the case why can we use if(memo[i] == 0) in this particular code and not wind up recomputing a bunch of values?
int fibonacci(int n){
return fibonacci(n, new int[n+1]);
}
int fibonacci(int i, int[] memo) {
if(i == 0 || i == 1) return i;
if(memo[i] == 0){ //This line does not make sense to me
memo[i] = fibonacci(i - 1, memo) + fibonacci(i - 2, memo);
}
return memo[i];
}
Since the only case where fib(i) should return 0 is when i = 0, then the test if (memo[i] == 0) is ok---it is never called for a value where 0 is an ambiguous result because of the first line of the function: if (i == 0.
Note what I think is more puzzling is why is the memoization array created in the wrapper call? Yes, the memoization saves computation for a given call, but all that optimization is lost between successive calls to the function.
if(memo[i]==0)
That if block implies that if fibonacci(n) has not already been computed (in which case the value in the i index will be 0), compute the value of fibonacci(n) and cache, but if it has already been computed and stored/cached (in which case the value in the i index would not be 0), do not compute again.
The reason for this is because, int array values are by default initialized to 0. You can see how here: Any shortcut to initialize all array elements to zero?

checking for unwanted input (Error Handling)

I want to check if the input my code needs is correct so I put a lot of if statements checking for the requirements and I can't figure out why it's not working. It is supposed to check if n is less or equal to 91 and / or it is a decimal (I don't want my input to be either). This is so that the user doesn't break the program by typing a decimal or a number higher than 91.
while (Error == 1) {
n = user_input.nextDouble();
if ((n - Math.round(n) <= 0.9) && (n - Math.round(n) >= 0.1)) {
System.out.println("Error: No Decimal points please, try again");
continue;
}
if ((n - Math.round(n) <= 0.9) && (n - Math.round(n) >= 0.1) && (n > 91)) {
System.out.println("Error: No Decimal points please, try again");
System.out.println("Error: Number too high, try again");
continue;
}
if (n > 91) {
System.out.println("Error: Number too high, try again");
continue;
}
if (n == Math.round(n)) {
Error = 0;
}
if (n == 0) {
break;
}
}
For some reason when I type 9.1 or 9.9 it doesn't do anything at all. It's blank...
I did >= which is supposed to check if it is bigger or equal to and <= which is supposed to check if it is less or equal to. Is that wrong?
Well, first of all, you seem to want only inputs that are integers less than or equal to 91.
It seems strange that you would say this, but then explicitly grab doubles with the nextDouble() method of Scanner.
There are better ways of checking for integers... see this question What's the best way to check to see if a String represents an integer in Java?
Either way, I'll assume you intend on sticking with your innovative methodology:
You are correct, that in regular math, 9.1 rounds to 9 and the difference between the two is less than or equal to 0.1. Your cases should work.
But welcome to the world of Java floating point algebra! Doubles don't compare well here.
What do I meant that they don't compare well? Well, the difference between your '9.1' and '9' is actually 0.09999999999999964, not 1.
Java doesn't compensate for this when you use basic comparators, so your comparison fails.
Hope is not lost! There is a better way of comparing doubles than using the regular comparison operators.
Introducing.... Double.compare()!! You can read the javadocs on that method, or you can go here for information on what that method does: some reliable tutorial site
However, what if they input 9.0001? Your test fails, even if the comparison works as you'd expect. You really should rethink your math here. As in, try this instead:
Double.compare((n - Math.round(n)),0.0) != 0)
In case of 9.1 and 9.9, none of the conditions are satisfied. That's why nothing is done. Loop is iterated and wait for next double input.
Here, the main culprit is n - Math.round(n). The calculations are not being accurate. For example, in case of 9.1:
n - Math.round(n) value is equal to 0.09999999999999964. So, the condition n - Math.round(n) >= 0.1 is never satisfied and no if block is reached.

Shorthand for "If greater than, then equal to" in Acttionscript?

Is there a shorthand method to write the following code? Often in games we want to make sure certain things dont leave a boundary, or more generally, we want to stop an index of an array from going beyond the bounds of an array. I've always written it this way, but am wondering if there is a shorthand in Actionscript, Java, or C#
In Actionscript:
index++;
if (index > array.length - 1) index = array.length - 1;
as far as I can tell, there is no operator that accomplishes this, though perhaps I am mistaken. I know the ternary operator is similar if (condition) ? value if true : value if false
You can use Math.min :
index = Math.min (index+1, array.length-1);
For the generic condition of if (condition) set variable (as opposed to your specific case) you could use the following:
variable = (condition) ? (set if true) : (set if false)
In your case, this turns in to:
index = index > array.length - 1 ? index = array.length - 1 : index;
It works in Java, Actionscript, and C#.
If your code looks like this (C#):
index++;
if (index > array.length - 1)
index = array.length - 1;
You're doing the equality testing no matter what anyway, so why not do it before the assignment?
if (index < array.Length)
index++;
I don't know of any shorter method in C#, but you could write your own extension to use, so you don't have to copy/paste the check throughout your code:
public static class ArrayExtensions
{
// Returns the index if it falls within the range of 0 to array.Length -1
// Otherwise, returns a minimum value of 0 or max of array.Length - 1
public static int RangeCheck(this Array array, int index)
{
return Math.Max(Math.Min(index, array.Length - 1), 0);
}
}
To use it:
var index = yourArray.RangeCheck(index);
Try the following, it's also more efficient because you won't make unnecessary increments:
if( index < array.length ) index++;

Java, comparing BigInteger values

BigInteger bigInteger = ...;
if(bigInteger.longValue() > 0) { //original code
//bigger than 0
}
//should I change to this?
if(bigInteger.compareTo(BigInteger.valueOf(0)) == 1) {
//bigger than 0
}
I need to compare some arbitary BigInteger values. I wonder which approach is correct. Given the above code which one should be used? The original code is on the top.. I am thinking to change it to the second approach.
The first approach is wrong if you want to test if the BigInteger has a postive value: longValue just returns the low-order 64 bit which may revert the sign... So the test could fail for a positive BigInteger.
The second approach is better (see Bozhos answer for an optimization).
Another alternative: BigInteger#signum returns 1 if the value is positive:
if (bigInteger.signum() == 1) {
// bigger than 0
}
If you are using BigInteger, this assumes you need bigger numbers than long can handle. So don't use longValue(). Use compareTo. With your example it better be:
if (bigInteger.compareTo(BigInteger.ZERO) > 0) {
}
This is not a direct answer, but an important note about using compareTo().
When checking the value of compareTo(), always test for x < 0, x > 0 and x == 0.
Do not test for x == 1
From the Comparable.compareTo() javadocs:
Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
Note:
A negative integer, not -1.
A positive integer, not 1.
True, checking for ==1 and ==-1 would work for BigInteger. This is the BigInteger.compareTo() code:
public int compareTo(BigInteger val) {
if (signum == val.signum) {
switch (signum) {
case 1:
return compareMagnitude(val);
case -1:
return val.compareMagnitude(this);
default:
return 0;
}
}
return signum > val.signum ? 1 : -1;
}
But it's still bad practice, and explicitly recommended against in the JavaDocs:
Compares this BigInteger with the specified BigInteger. This method is provided in preference to individual methods for each of the six boolean comparison operators (<, ==, >, >=, !=, <=). The suggested idiom for performing these comparisons is: (x.compareTo(y) <op> 0), where <op> is one of the six comparison operators.

Categories