How can I write this variable in the right way? - java

I have to write in Java (with Cplex) the variable x[i][j] that is the sum on k of x[i][j][k].
i,j and k are the indices of three sets.
I have already declare x[i][j][k], but i would like to know the right expression.
Thanks

You appear to be confusing yourself regarding the type of x[i][j]. Is it a set with several elements, indexed by k, or is it a number representing their sum? You seem to start out this step in computation with the first answer and conclude with the second.
A solution to this is to use another variable to store the result, maybe something like:
sums[i][j] = sum(x[i][j]);
where sum(list) is a function that takes in a list, starts with a return value of 0, and iterates over the elements of the input list adding each one to the return value, then returns that value. You can check here for some ideas about how to implement that.

Related

How to make zeros for next n-1 elements of n similar elements in an array?

I have an integer 667778 and I need to output it as 607008.
I used an array 6,6,7,7,7,8 and xor next similar elements.
I need to this in constant time.
suppose
int arr[]={6,6,7,7,7,8}
int ele=arr[0];
for (int i=1;i<arr.length;i++)
{
if(arr[i]==ele)
arr[i]=0;
else
ele=arr[i];
}
output array arr has [6,0,7,0,0,8]
It is taking O(n) n is size of the array
How can i do this in constant time?
Unless the number given will always be 6 digits (in which case you can hard code it, which is technically constant time, but will give equal performance to the loop), then you can't get constant time because the basis of the problem requires looping through the array in the first place.
Is there are reason you want it to work in constant time anyways, as O(n) is the fastest a program can read the data anyways.
Edit:
After reading your comments, I think you need to come up with a different approach so calculating the XORs won't be inside the loop. I can't provide much more help without the original problem.

Problem with doubles as key in HashMap in Java

I came across an interview question for which I am not sure what the correct answer is.
The problem is below.
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
The way I solved it by looping through the element and storing the diff between target and element as key and index of the current element in a map.
Then later on when the diff appears in the array, I can look up in map which element has this diff and at what index in the map.
Up to now it is fine.
However, for a follow-up question, "What if the elements are double"
I am not sure what is the issue if any.
When searching I came across a couple of posts mentioning correct way to compute a hashcode using logical shift and using or. However, I see the similar logic is used in Java's Double.hashcode function.
I thought that the problem could be when computing diff, there might be precision loss. Hence, it might end up mapping to a different hash bucket.
However, when I tried, I couldn't come up with such an input. What is the actual problem? And how do I test/solve it?
Java
I tried simply changing the numbers to double, but the logic worked fine.
This program illustrates the problem, with a two element array:
public strictfp class Test {
public static void main(String[] args) {
double in[] = {1e10, Math.nextUp(1e10)};
double target = 2e10;
System.out.println(in[0]+in[1]);
double diff = target-in[0];
System.out.println(diff);
System.out.println(in[1] == diff);
System.out.println(in[0]+in[1] == target);
}
}
output:
2.0E10
1.0E10
false
true
The problem is that your logic assumes that there is only one value that, when added to an element of your array, gives the target sum. Because of rounding, with double elements, there can be multiple values that give the same sum.
In my example, the sum of the two elements of the array is equal to the target, but the second element is not equal to the difference between in[0] and the target.
My first thought on a solution to the floating point version of the problem is as follows:
Create an array of ordered pairs containing value and index.
Sort by value.
For each element x, do a binary search for an element y such that x.value + y.value is equal to the target.
If you find one, return [x.index, y.index]
This is O(n log(n)) where the int version was O(n).

Double Recursion in one method Java

I am pretty sure that I thoroughly understand how the methods with only one recursion work.
Ex) calculating factorial
public int factorial(int n){ //factorial recursion
if(n==0){
return 1;
}
else{
return n*factorial(n-1);
}
}
For these methods, I can even picture what's going on in the stacks and what values are being returned at each stack level.
But Whenever, I encounter methods with Double Recursions, the nightmare begins.
Below is a recursion problem with double recursions from coding bat.
Ex) Given an array of ints, is it possible to choose a group of some of the ints, such that the group sums to the given target? If yes, true. If no, false.
You use 3 parameters; starting index start, An int Array nums, target int value target.
Below is the solution for this problem.
public boolean groupSum(int start, int[] nums, int target) {
if (start >= nums.length) return (target == 0);
if (groupSum(start + 1, nums, target - nums[start])) return true;
if (groupSum(start + 1, nums, target)) return true;
return false;
}
My take to understand this solution is this. Say I was given an array {2,4,8} with starting index = 0, and target value 10. So (0,{2,4,8},10) goes in through the method, the function gets re-called at
if (groupSum(start + 1, nums, target - nums[start])) return true;
so it becomes (1,{2,4,8},8) and it does over and over until start index hits
3. when it hits 3. The stack at the last level(?) goes to the second recursive call. And this is where I start losing track of what's happening.
Can anybody break this down for me? And when people use double recursion,(I know it's very inefficient and in practice, almost no one uses it for its inefficiency. But just in an attempt to understand it.)can they actually visualize what's going to happen? or do they just use it hoping that the base case and recursion would work properly? I think this applies generally to all the ppl who wrote merge sort, tower of hanoi alogrithm etc..
Any help is greatly appreciated..
The idea of a double recursion is to break the problem into two smaller problems. Once you solve the smaller problems, you can either join their solutions (as is done in merge sort) or choose one of them - which is done in your example, which only requires the second smaller problem to be solved if solving the first smaller problem didn't solve the full problem.
Your example tries to determine if there is a subset of the input nums array whose sum is the target sum. start determines which part of the array is considered by the current recursive call (when it's 0, the entire array is considered).
The problem is broken to two, since if such a subset exists, it either contains the first element of the array (in which case the problem is reduced to finding if there's a sub-set of the last n-1 elements of the array whose sum is target minus the value of the first element) or doesn't contain it (in which case the problem is reduced to finding if there's a sub-set of the last n-1 elements of the array whose sum is target).
The first recursion handles the case where the subset contains the first element, which is why it makes a recursive call that would look for the target sum minus the first element in the remaining n-1 elements of the array. If the first recursion returns true, it means that the required subset exists, so the second recursion is never called.
The second recursion handles the case where the subset doesn't contain the first element, which is why it makes a recursive call that would look for the target sum in the remaining n-1 elements of the array (this time the first element is not subtracted from the target sum, since the first element is not included in the sum). Again, if the second recursive call returns true, if means that the required subset exists.
Well if you want to visualize it, usually it's kind of like a tree. You first follow one path through the tree until the end, then step one back and pick a different path (if possible). If there is none or you are happy with your result you just take another step back and so on.
I don't know if this helps you but when I learned recursion, it helped to just think of my method as already working.
So I thought: Great, so basically my method is already working, but I can't call it with the same parameters and have to make sure I return the right value for these exact parameters by using different ones.
If we take that example:
At first we know that if we have no numbers to look at left, then the answer depends on if the target is 0. (first line)
Now what do we do with the rest? Well... we'd need to think about it for a moment.
Just think about the very first number. Under what circumstances is it part of the solution? Well that would be if you could create target-firstnumber with the rest of the numbers. Because then when you add firstnumber, you reach target.
So you try to see if that's possible. If so, it's solvable. (second line)
But if not, it's still possible that the first number just isn't important for the solution. So you have to try again to build the target without that number. (third line)
And that's basically all there is to this.
Of course to think like this you need two things:
1. You need to believe that your method already works for other parameters
2. You need to make sure your recursion terminates. That's the first line in this example but you should always think about if there is any combination of parameters that will just create an endless recursion.
Try to understand it like this: Recursion can be rewritten as a while-loop. where the condition of the while is the negation of the stop-condition of the recursion.
As already said, there is nothing called double recursion.

Return Array index and increment at the same time

How does Java, Kotlin, and Android handle returning an Array value at a given index while incrementing the index value?
int[] someArray = new int[5];
int index = 0;
int result;
result = someArray[index++];
Which index would be passed to the result? Will it increment index first, then pass it to someArray[1], or will it pass the original value of index to someArray[0] and then increment index?
See: Java documentation, Assignment, Arithmetic, and Unary Operators:
The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value.
So you'll get someArray[0].
index++ returns index and then increments by 1. So it will do result = someArray[0] and then set index to 1.
In contrast, ++index would do the increment and then pass the incremented value. So if you wanted result set to someArray[1] in the above code, you would use ++index.
As someone else said, please don't use this kind of syntax. Instead, please write
index++;
result = someArray[index];
In Java and similar languages, using index++ only increment the value after the expression has been evaluated. If you want to increment before using the variable, use ++index.
In this case, it will use the original value of index to obtain result, and then increase its value to 1.
It will pass someArray[0] and then increment index
It is not dependent from android, the general rule is:
index++ means evaluates index and then increment it, while ++index is increment then evaluate
1.) Avoid doing this sort of thing, in fact with code I review I ask people to never do this.
Not specifically using ++, but the fact you're doing it as part of evaluating something else. Generally it won't cost the compiler any extra to have that increment as a separate statement, and putting it inline like that means the next person coming along has to take a second and evaluate the increment themselves.
I know it's minor, and it's a little nitpicky, but stuff like this costs extra time during code review, it's easy to miss while scanning, etc. And it saves you nothing but a few extra keystrokes, which when compared against code clairity and readability is not worth it IMO.
2) You will get someArray[0], and after moving on to the next line, you will have your index incremented.

Storing values within a hashmap

I am trying to code a frequency analysis program for fun. I currently have everything being stored in a hashmap and I index the values using an iterator.
My values however are stored as integers, how could I go about converting these entries into percentages, or a more accessible format so i can compare them later?
I was thinking i could use getValue(), but this is an object.
Can anyone point me in the right direction? Should i be using a hashmap? should i transfer them into an array the size of the hashmap?
Hashmaps are indeed ideal for building freuqency tables, and the value type should definitely be Integer (if you try to store percentages, you'd have to update all percentages each time you add a new value). If you have another class that contains the hashmap as a field, you could make a method for retrieving the percentage of a specific character (note that I don't recall the exact method names):
public float getPercentage(char c) {
if (!map.containsKey(c))
return 0;
int sum = 0;
for (Integer count : map.values())
sum += count;
return map.get(c) / (float)sum;
}
If you want the percentages for all characters, you should make a method that produces a new hashmap that contains the percentages, calculated in a similar fashion. If you want to be fancy (read: overengineer), you could even implement an Iterator that produces percentages from the original Integer hashmap.
I'm assuming you have a map of the form {'A':5, 'B':4, etc} meaning A appears five times in your text, B four times, etc.
In that case, to calculate the frequency of a given letter, you need to know the total number of letters in the map (i.e. 9 in the example above). You can do this one of two ways:
Iterate over the entire map, and sum up the values
Keep a running count of the number of times you add something to the map, so you can use it later.
Both are reasonable solutions to the problem. I'd prefer option 2, especially if you are doing things interactively, whereas option 1 might suffice in a batch mode setting.
You should parametrize your hashmap so that getValue() returns an Integer. You could use the object type Float if you would like a percentage instead.

Categories