How to get values of vars by its name - java

I'm using the CPLEX Java interface to do some MIP problems, the optimizer is doing well but I can't get values of vars by their names.
The definitions of my vars are in a for loop, so in the outer code, I can't use cplex.getValue() function to get their values.
Please remind me of any methods that can get all the values or get values by their names.
for (int i = 0; i < count; ++i){
// c1 is changing when i increase
IloNumVar[] x = new IloNumVar[c1];
for (int j = 0; j < c1; ++j) {
x[j] = cplex.numVar(0, 1, IloNumVarType.Int, "x" + String.valueOf(i) + "_" + String.valueOf(j));
}
}
...
cplex.solve();
How to retrieve all x values outer for loop after cplex.solve()?

Just don't try to recover them by their names. Keep your CPLEX variables in lists, arrays, dictionaries, structures, class instances or whatever in your code. Your IloNumVars are just normal objects that can be stored like any other. In your example code, just keep those IloNumVar arrays in a structure declared outside the loop (e.g. a list of those IloNumVar[] arrays).
If you really need to retrieve them by name, then put them in a dictionary, keyed on the variable name - again that would have to be declared outside your loop above. But that would be less efficient than just keeping them in your usual Java data structures as it would require extra lookup processing inside the ictionary to find the item by name.

Related

Distinguishing local variables with same name in a loop

I have found the following java code:
test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" : "Didn't find it");
}
Inside the loop, the above code is creating 'n', 'j' and 'k' several times. How the program distinguishes between these variables of the same name?
I mean where they are stored in the memory to distinguish them?
With a bit of simplification:
Inside a { ... } block, int k = 0; creates a variable, and that variable exists up to the moment where you reach the end of the block, and there the variable gets destroyed. So, at any time during the program run, there's at most one n, j, or k in existence.
A bit closer to reality:
The compiler scans the whole method, finds the list of variables that might exist in parallel (i, n, j, k, and foundIt), and allocates enough places on the stack for these variables (5 places in your example). These stack places exist from the moment you enter your method until you return from it, but they are not used all the time, e.g. the k place only contains useful values from the time you execute int k = 0; to the end of the current loop iteration.
Java's local variables have a protection known as definite assignment this means that you can't read a value from them before you've assigned it a value.
They are also defined within a scope: you can only access the variable within a certain chunk of the program.
With the two of these things together, you don't need a separate variable for each iteration of the loop: you are guaranteed to assign a local variable a value before using it, so you are guaranteed to overwrite any value which was stored in it before, if any.
Variables are really just a helpful concept in the source code. Once compiled, the byte code doesn't have variable names: the compiler has simply determined that it can temporarily use a particular part of memory to store a value for a limited time. It will reuse this memory many times, but in ways that it guarantees do not overlap between usages.

Using temporary variables to manipulate values in array

So say I have an array with columns {item, quantity}. I am getting these values from an sql table, then sorting them by item. I am using a temporary variable "quantity" to manipulate the double value:
while(rs.next()){
item = rs.getString(1);
for(int i = 0 ; i < array.size ; i++){
if(item.equals(array[i][0]){
double quantity = rs.getDouble(2);
quantity = quantity + Double.parseDouble(array[i][1]);
array[i][1] = quantity;
}
}
//add code for adding items if not found in array
}
My question is will using this temporary variable be slower/create garbage while it iterates the array? Does Java properly dispose of this variable at the end of the if statement? I am asking because I am having issues with heap space, and I do not want to have to rewrite everything to accomodate this.
My other option is:
if(item.equals(array[i][0]){
array[i][1] = String.valueOf(Double.parseDouble(array[i][1]) + rs.getDouble(2));
}
Thanks for reading
It will always override quantity with new value, when old value will be keep of course in array. Quantity won't have impact on your memory especially that this is primitive.
If you will deal with complex type and you will do something like that, you will override with every loop the reference to object, so in array you will have all the time reference to same object.

Using Strings to Call Methods in Java

This is one of the first programs I am writing by myself. I want to make a physics calculator where many objects can interact with each other and give the user an option to add more objects. My idea is to have a for loop that runs through each object pulling on each other like this.
for(int n=1; n<=totalObjs; n++){
objName = "object"+n;
for(int i=1; i<n; i++){
obj2Name = "object"+i
objName.getMass();
//getting mass and position from both
//calculations here}
for(int x=n+1; x<=totalObjs; x++){
//same stuff as in the previous for loop}
}
I know there are probably huge syntax errors or logical errors in that but I'd like to sort through those on my own. Is there some way i could reference objects with the strings?
Is there some way i could reference objects with the strings?
Yes, via a Map<String, SomeType> such as a HashMap<String, SomeType>.
Think of this as being similar to an array or ArrayList, but instead of using number indices, you'd be using String indices.
Now looking at your code however, you might be better off using a simple ArrayList or array, since you appear to be trying to use numeric indices.
e.g.,
// assume a class called GravMass which has Mass, position, and momentum
List<GravMass> gravMassList = new ArrayList<GravMass>();
// fill your list
for(int i = 0; i < gravMassList.size() - 1; i++) {
GravMass gravMass1 = gravMassList.get(i);
int mass1 = gravMass1.getMass();
for(int j = i + 1; j < gravMassList.size(); j++){
GravMass gravMass2 = gravMassList.get(j);
int mass2 = gravMass2.getMass();
//getting mass and position from both
//calculations here}
}
}

For loop counter in dot operator

I'm working in the Android ADT plugin for Eclipse.
What I try to do is this:
I have some drawables named from 0 to 150 and i want to get them into an array to use them.
As far as I know, to be usable, they have to be assigned with
"R.drawable.FilenameWithoutExtension".
To make the array creation easy and fast I want to use a for loop:
for (int i = 0; i <= 150; i++) {
imagesArray[i] = R.drawable.i;
}
But for now I get an error for that "R.drawable.i" because there is no file "i".
Is there a way to use the numeric value of "i" instead of the letter for the assignement "R.drawble."?
You can get a resource identifer from its name using the getIdentifier() method:
for (int i = 0; i <= 150; i++)
imagesArray[i] = getResources().getIdentifier(String.valueOf(i), "drawable", "your.package.name");
The file names must start with a letter because at build time the file names are converted to java identifiers.
After you do that you can use reflection access each of the members of R.drawable.

Accessing array in a return method

Good evening people,
I have a method that creates, populates, and returns an array to the function call as so:
public double[] getTotalDistances(){
double[] distance;
distance = new double[3];
for(Activity r: diary ){
if(r instanceof Run){
distance[0] += r.getDistance();
}
}
return distance;
}
and i can't seem to find a way to access this returned array to print it out in the main method, i have tried this: (where m is the object i have instantiated)
for(int i = 0; i< m.getTotalDistances().length; i++){
System.out.println(m.getTotalDistances().distance[i]);
}
this says it cannot find the variable distance.
i am aware that i can do something like:
for(double i: m.getTotalDistances()){
System.out.println(i);
}
this will print out the returned array, however, i would like to know how to do it in the "classic" way.I know that this must be extremely novice, but i couldn't find an answer. Any kind of help will be greatly appreciated.
It should be m.getTotalDistances()[i] and not m.getTotalDistances().distance[i]
Use a variable to store it before iterating.
double[] distance = m.getTotalDistances();
for(int i = 0; i < distance.length; i++){
System.out.println(distance[i]);
}
Your approach would call your getTotalDistances() method over and over inside the loop. You only need it once to work with.
You get this error
this says it cannot find the variable distance.
because the variable distance is only known in the scope of your method getTotalDistances() and thus you cannot use it outside of that (and it wouldn't make sense either).
The way it is written, distance is not defined. You will need to create a pointer the the returned value if you want to reference it.
double[] distance = getTotalDistances();
for(int i = 0; i < distance.length; i++) {
System.out.println(distance[i]);
}
Also, as it is written, any values other than the first will always be 0, and an accumulator makes more sense.
Another thing to note is that, as it is written, getTotalDistances() will run twice on each iteration of your for loop; once for the condition and again for the println(). If you were to scale this concept to a larger use case, the performance implications would be huge.

Categories