Modeling the Objective Function in the CPLEX Java API - java

I#m trying to model the objective function sum(i in Sites,j in Sites, k in Routings)(c[i][j] * x[i][j][k]*TruckKmCost) in Cplex using java.
IloLinearNumExpr expr = cplex.linearNumExpr();
for (int i = 1; i <= nbFarmer; i++) {
for (int j = 1; j <= nbFarmer; j++) {
for (int k = 1; k <= nbRouting; k++) {
expr.addTerm(truckKmCost, c[i][j],x[i][j][k]);
}
}
}
This was my attempt, but the method addTerm only accepts (double, IloNumVar), and I can't convert c[i][j] to IloNumVar, because I need it as an int so i can add my int values to it.
There must be a pretty easy solution, maybe somebody can help me, I'm a little stumped right now.
Thanks a lot!

You did not specify whether c[i][j] is a variable or a number. Depending on this there are two different solutions to your issue:
In case c[i][j] is a number then just write expr.addTerm(truckKmCost * c[i][j], x[i][j][k]), that is, merge the two numbers into one single argument to addTerm.
In case c[i][j] is a variable then your objective is not linear but quadratic. In that case you cannot use IloLinearNumExpr but have to use IloQuadNumExpr. The addTerm() of this class takes two variables as arguments.

Related

Mathematical equivalent of multiple nested loops

When you have loop in the loop or nested loop, let`s say for-loop, regardless of the programming language(of course must be imperative)
for(int j = 1; j <= 100; j++){
for(int k = 1; k <= 200; k++){
\\body or terms
}
}
is the mathematical equivalent, when I want to sum it for i = 1 with all j = {1, 200} and i = 2 with again all j = {1, 200} and so on :
And the red-circled condition is unnecessary, right?
And the same applies for multiple nested loops?
The code you provided will run as you explained
sum it for i = 1 with all j = {1, 200} and i = 2 with again all j = {1, 200} and so on
However, the mathematical equivalent is without the condition marked in red.
The sigmas with the condition is equivalent to this code:
for(int j = 1; j <= 100; j++){
for(int k = 1; k < j; k++){
\\body or terms
}
}
Hope I helped.
Sigma stands for summation, which means that if you're dealing with sigma for a range, i=1,n, which is defined as x, then the result is going to be x * n (x + x + x + ... + x n times). Transcribed to pseudocode, it would be like this:
result = 0
for i=1,n:
result = result + x
So it doesn't really translate to a general for loop which is more about doing something a certain number or times or until a condition is met.
Often when you see mathematicians researching algorithms that relate directly to software fields, they use the more flexible functional notation and recursion a lot more than summation since such a functional notation actually translates a bit more directly to general loop computations than summation.

Having trouble multiplying two matrices

Sorry,this is a homework problem. I am not good with maths, so I checked out some videos to understand how two matrices are multiplied. I came up with a formula, but I do not know what I am doing wrong? This question has been answered before, but I did not understand. Thank you.
case 3:
System.out.println("THE PRODUCT OF TWO MATRICES ARE: ");
for(i =0; i< arrayList.length; i++){
for(j =0; j< arrayList1.length; j++){
for(k =0; k < arrayList1.length;k++){
multiplication = arrayList[i][k] * arrayList1[k][j] + multiplication;
}
System.out.print(arrayList[i][j]+" ");
}
System.out.println();
}
break;
First of all you should understand that the multiplication of two matrices should result in a matrice (which not appear to be the case with your multiplication variable).
I suppose you have to program the basic implementation. Let's take a look at the following matrices.
A has n rows, and m columns; said to be a matrice n x m.
Similary, B has m rows and p columns (m x p matrice). The multiplication of A x B will give you a matrice n x p.
Note that if you want to do the multiplication A x B, the matrice A must have the same number of columns that the number of rows of the matrice B.
Now each value in the matrice AB (ith row and jth column) is computed as follow:
That said, let's take a look at the Java implementation (which is a pure translation of the mathematical formula).
public static int[][] multiply(int[][] matrixA, int[][] matrixB) {
int[][] result = new int[matrixA.length][matrixB[0].length];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++) {
for (int k = 0; k < matrixB.length; k++) {
result[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}
return result;
}
The result matrice is initialized at the right dimensions. Then the first two nested loop (with indices i and j) will loop through all the elements of elements of the resulting matrice. Then you just need the third loop to compute the sum.
You'd still need to check that the matrices you give as parameters have the correct length.
The algorithm used is pretty naive (O(n3) complexity). If you don't understand it, there's a lot of resources in the web that explains how it works; but that would more a mathematical question than a programming one.
Hope it helps ! :)

Summation and deriving expressions for runtime

I have the following code. I have to derive expressions for the runtime using summations, then solve them to obtain an expression for T(n) or T(n,m) that is not written with a summation. Then count how many times the println statement is executed as a function of any variables n and or m. O() is used to check answers.
T(n) E O(n)
for (int i = 0; i < n; ++i)
{
System.out.println("hello");
}
I've got the summation part of this to get...
Sigma i=0 lower bound, n is upper bound, and println is the constant.
From here, how do I solve this to get an expression for T(n)?
Here is another coding example of code where I found the summation but do not quite understand the second part of the question.
T(n) E O(n^2)
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= n; ++j)
{
System.out.println("Hello");
}
}
Would like some help on the steps to go along with an answer.

Java Prime calculator according to Sieve of Eratosthenes

I've stumbled on the following problem: I have a class to get and print all primes between 1 and N. The N is a parameter which you have to insert by yourself. When I insert 10000 for N, the code works and prints out all primes out from 2 to the closest prime to N.
When I insert 40000 the code still works. When I insert 50000 (or higher), the code gives an ArrayOutOfBoundsException. Why?
This is the code I use:
ArrayList<Integer> priemGetallen = priemGetallen(n);
for (Integer i : priemGetallen) {
System.out.println(i);
}
And uses
ArrayList<Integer> priemgetallen = new ArrayList<Integer>();
for(int i = 2; i < n; i++){
priemgetallen.add(i);
}
for (int i = 2; i < n; i++) {
for (int j = i; j * i <= n; j++) {
if((j*i) < priemgetallen.size()){
priemgetallen.remove(j*i);
}
}
}
return priemgetallen;
}
The point "priemgetallen.remove(j*i)" is where I receive the error.
I'd really appreciate it if someone can tell me why this doesn't work for all N's bigger then approx. 40000.
Thanks in advance!
The maximum value a Java int can hold is 2,147,483,647, so j * i is overflowing when i and j reach 46,341.
To extend the range, change the types of i, j and n to long.
See How does Java handle integer underflows and overflows and how would you check for it?
P.S. You'll also need to change priemgetallen into an array list of Long rather than Integer.

Java cannot find symbol for loops, logic problems?

Ok, my program in this specific section takes a line of data from a studentAnswer string array, the value of which would be something like TTFFTFTFTF. I am supposed to take this, and compare it against a key array, which might look like TFFFTFTFTF. A student takes a quiz, and my program calculates the points correct.
My intention is to use a separate points array to find the numeric grade for the student. The index of studentAnswer refers to a specific student. So studentAnswer[i] is TTFFTFTFTF. I use substrings to compare each individual T/F against the correct answer in key[], which would have a single T/F in each index. Then, if they are correct in their answer, I add a 1 to the correlating index in points[] and will later find the sum of points[] to find the numeric grade out of ten.
My problem here is that String origAns, used to define the student's original answer string, is getting a Java Error cannot find Symbol. I have tried placing the instantiation of origAns within each different for loop, but I can't get the program to work. Int i is meant to follow each specific student- I have four parallel arrays that will all log the student's ID number, numeric grade, letter grade, and original answers. So that is the intention of i, to go through each student. Then j should be used to go through each of these original student answer strings and compare it to the correct answer...
Logically, it makes sense to me where I would put it, but java doesn't agree. Please help me to understand this error!
for (int i = 0; i < studentAnswer.length; i++){
String origAns = studentAnswer[i];
for (int j = 0; j < key.length; j++){
if (origAns.substring[j] == key[j]){
//substring of index checked against same index of key
points[j] = 1;
}
if (origAns.substring[j] != key[j]){
points[j] = 0;
}
}
}
It sounds like you're trying to call the substring method - but you're trying to access it as if it were a field. So first change would be:
if (origAns.substring(j) == key[j])
Except that will be comparing string references instead of contents, so you might want:
if (origAns.substring(j).equals(key[j]))
Actually, I suspect you want charAt to get a single character - substring will return you a string with everything after the specified index:
if (origAns.charAt(j) == key[j])
... where key would be a char[] here.
You can also avoid doing the "opposite" comparison by using an else clause instead.
You should also indent your code more carefully, for readability. For example:
for (int i = 0; i < studentAnswer.length; i++) {
String origAns = studentAnswer[i];
for (int j = 0; j < key.length; j++) {
if (origAns.charAt(j) == key[j]) {
points[j] = 1;
} else {
points[j] = 0;
}
}
}
And now, you can change that to use a conditional expression instead of an if/else:
for (int i = 0; i < studentAnswer.length; i++) {
String origAns = studentAnswer[i];
for (int j = 0; j < key.length; j++) {
points[j] = origAns.charAt(j) == key[j] ? 1 : 0;
}
}
When you call a method in Java, you use parentheses () instead of brackets [].
Since substring is a method, you should call it like so
if (origAns.substring(j) == key[j])
A few other notes, you should use the equals method for comparisons (especially those comparisons involving Strings.)
if (origAns.substring(j).equals(key[j]))
Also, you should use charAt to extract a single character at some position in a string. substring(j) will return a string of characters starting at position j.
if (origAns.charAt(j).equals(key[j]))
Your explanation is very long and I have not read it from the beginning to end. But I can see at least one problem in your code:
if (origAns.substring[j] == key[j])
You are comparing strings using == instead of using method equals():
if (origAns.substring[j].equals(key[j]))
Substring is a function, not a member, of String objects. Check out the example at the top of this page:
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html
Notice the use of parenthesis instead of brackets.
If you are using a String use charAt function
String studentAnswer = "TTFFTFTFTF";
for (int i = 0; i < studentAnswer.length(); i++)
{
char origAns = studentAnswer.charAt(i);
}
Else if you are using an char array then
char studentAnswer[] = "TTFFTFTFTF".toCharArray();
for (int i = 0; i < studentAnswer.length; i++){
char origAns = studentAnswer[i];
}

Categories

Resources