I've found a Choco solver as constraint programming software working with Java. I would like to learn it more. I have done some basic example. But now I would like to try something more complex (Pritsker project scheduling alg) and I need your help. In order to progress I have to understand how to put constraints on rows of matrix variable. Exactly I need to keep a sum of rows equal 1 (task starts only once). I have tried it but unsuccessfuly. Could you help? I do use Choco 2.1.5 My matrix is as follows:
int n = 10; // projects
int m = 12; // time horizon in months
IntegerVariable[][] x = new IntegerVariable[n][m];
int i, j;
for (i = 0; i < n; i++){
for (j = 0; j < m; j++){
x[i][j] = Choco.makeIntVar("x_" + i +"_" + j, 0, 1, Options.V_ENUM);
model.addVariable(x[i][j]);
}
}
You should define variables as rows and columns first.
Than, you may use this documentation to proceed. Something like this might be helpful:
IntegerVariable[][] rows;
int n; //number of rows
for(int i=0; i<n; i++)
model.addConstraint(eq(sum(rows[i], 1));
To add constraint over the rows, you should transpose the matrix and apply the constraint over the lines :
transposed = ArrayUtils.transpose(x);
for(int i=0; i<n; ++i){
model.sum(transposed[i], "=", 1);
}
Related
I would like to take sets of every 3 elements from table, and then use them for some calculations. Let's say that my table is really big, e.g. 1000+ elements.
Tab elements are like like {x1,y1,z1,x2,y2,z2,...}.
I want to take the first three elements, do some calculations with them, take the next three elements, etc.
Here is my code so far:
double x=0;
double y=0;
double z=0;
for (int i =0; i<tab.length; i++)
x= (double)tab[i];
for (int j =0; j<tab.length; j+=2)
y= (double)tab[j];
for (int k =0; k<tab.length; k+=3)
z= (double)tab[k];
deathstar(x, y, z);
This is using only last 3 elements from tab and deathstar is printing calculation made only on last 3 elements. I was playing around with {}, but it didn't give me results that i wanted. Anyone have any solid idea how to take out every 3 elements from my table ? tab is defined outside of this code and is of type int[].
Thank You in advance for any thoughts about given issue.
Lose the increment part of the loop and increment after each element is gotten.
for (int i =0; i<tab.length;) {
X=(double)tab[i++];
Y=(double)tab[i++];
Z=(double)tab[i++];
//do something
}
This will grab three consecutive elements at a time and then do the calculation. Also checkS to make sure it won't go out of bounds.
double x=0;
double y=0;
double z=0;
int j = 1;
int k = 2;
for (int i =0; i<tab.length; i++)
{
if(i + j < tab.length && i + k < tab.length){
x= (double)tab[i];
y= (double)tab[i + j];
z= (double)tab[i + k];
deathstar(x, y, z);
}
}
You're missing a { after the last for, and so deathstar is only called after all loops finished. Better use { for every for-loop. You could find this easily using a Debugger.
Next, you will ask what's wrong with the logic and why yoou don't get the expected result, because now you would get deathstar(x1,y1,z1), deathstar(x1,y1,z2),.... Try the following (note: I'm assuming the length of tab is indeed a multiple of 3):
for(int i = 0; i < tab.length; i += 3) {
x = tab[i];
y = tab[i+1];
z = tab[i+2];
deathstar(x, y, z);
}
This way your code looks much cleaner.
for (int i =3; i<tab.length; i+=3){
tab[i-1]
tab[i-2]
tab[i-3]
}
maybe this approach will help you
Okay probably it's a very easy solution, but I can't seem to find it. I've got two ArrayLists:
ArrayList<Candidate>partyList and ArrayList<Party>electoralList
Now I want to make a 2d int array that represents the parties and candidates like this:
p c
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
etc.
I think I already have the right for-loop to fill the array but I only miss the correct formula to do it.
int[][]ArrList;
for (int i=0; i<parties.size(); i++){
for(int j=0; j<parties.get(i).getPartyList().size(); j++){
ArrList[i][j]=
Is the for-loop indeed correct? And what is the formula to fill the array then?
I will try and answer the question from how I understood what you are looking for here.
You should understand this first:
A 2D array consists of a nestled array i.e. ArrList[2][3] = [ [1,2,3], [1,2,3] ] -> The first digit declares How many arrays as elements, the second digit declares Size or if you like: length, of the array elements
If you are looking for to represent the candidates and parties as numbers. Here is my solution:
int[][]ArrList = new int[parties.size()][electoral.size()]
for (int depth=0; depth < parties.size(); depth++){
for(int itemIndex=0; itemIndex<parties.get(depth).getPartyList().size(); itemIndex++){
ArrList[depth][itemIndex]= itemIndex;
I hope this is what you were looking for.
First of all, ArrList should not have a starting capital letter (it is not a class but an object).
Second point (I think what troubles you) is that you are not initializing the matrix and the parties.size() are always 0. I am not sure since there is not enough code though.
You could do something like this
int ROWS = 10;
int COLS = 2;
int [][] matrix = new int[ROWS][];
for(int i=0; i< matrix.length; i++){
matrix[i] = new int[COLS];
}
or, with lists
int ROWS = 10;
int COLS = 2;
List<List<Object>> matrix = new ArrayList<>(ROWS);
for (int i = 0; i < ROWS; i++) {
ArrayList<Object> row = new ArrayList<>(COLS);
for (int j = 0; j < COLS; j++) {
row.add(new Object());
}
matrix.add(row);
}
int[][] arrList=new int[parties.size()][2];
int i=0,j=0,k=0;
for(;i<parties.size();i++,j++){
if(j==1){
arrList[k][j]=electoralList .get(--i);
j=-1;
k++;
}
else{
arrList[k][j]=parties.get(i);
}
}
arrList[k][j]=aarM.get(electoralList .size()-1);
System.out.println(Arrays.deepToString(arrList));
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 ! :)
There is a really easy way to access the rows of a 2D array in java
for (int i = 0 ; i < integer2D.length ; i++)
getMyArray(integer2D[i]);
But, I searched in the web to find such easy way to iterate on columns of the 2D-array, like
for (int j = 0 ; j < integer2D[0].length ; j++)
getMyArray(integer2D[][i]);
or
for (int j = 0 ; j < integer2D[0].length ; j++)
getMyArray(integer2D[...][i]);
which works in some programming languages. I just found the class RealMatrix and MatrixUtils that I can convert my array2D to a real matrix and then transpose it and again convert it to an array and iterate on it. But I suppose that there exist a simpler way?
Edit: iterating on rows as I noted in the first piece of code is easy but the main question is how to iterate on columns like the second and third codes work in some other programming languages.
Edit2: As I mentioned in the last paragraph of the main question, the easiest way that I know is transposing the matrix and the iterating on its rows.
If I understand your question, you could use a for-each as an easy way to get each row like
for (int[] row : integer2D) { // <-- for each int[] in the int[][]
for (int val : row) { // <-- for each int in the int[] row
// ...
}
}
For this, you can use the BigMatrixImpl Class of the commons math library. It has a getColumnAsDoubleArray() method which will return the specified column as an array.
Delivering only one index will give you the whole row, so:
integer2D[5] // returns an int[]
will give you an integer array, which is the 6th row in your matrix.
If you supply both indexes directly you get the value of the "cell"
integer2D[5][1] // returns an int
will give you the value of the second column of the 6th row.
This is direct access to your matrix, if you want to iterate through the rows the answer from Elliott is what you are looking for.
Edit: Transposing:
int width = array.length;
int height = array[0].length;
int[][] array_new = new int[height][width];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
array_new[y][x] = array[x][y];
}
}
I don't know if this is a stupid question, but I need to dynamically change the number of for-loops without using recursion.
For example, if n=3, I need 3 nested for-loops.
for(int i=0; i<size; i++){
for(int j=0; j<size-1; j++){
for(int k=0; k<size-2; k++){
//do something
}
}
}
If n=5:
for(int i=0; i<size; i++){
for(int j=0; j<size-1; j++){
for(int k=0; k<size-2; k++){
for(int l=0; l<size-3; l++){
for(int m=0; m<size-4; m++){
//do something
}
}
}
}
}
Is there any way to achieve this without recursion?
Another question: what is the use of Multiple Dispatch in Java? I'm trying to code something in ONE METHOD, and it should run different events in different cases of the parameter. NO IF STATEMENTS / TERNARY OPERATORS / CASES.
NOTE: I can ONLY have one method (part of the problem), and cannot use recursion. Sorry.
Think about how many times you run through this loop. It looks like (size!) / (size - n)!:
int numLoops = 1;
for (int i = 0; i < n; i++) {
numLoops*= (size - i);
}
for (int i = 0; i < numLoops; i++) {
//do something
}
It depends what exactly you're trying to do. Recursion can always be replaced with iteration (see this post for examples using a Stack to store state).
But perhaps the modulo (%) operator could work here? i.e. Have a single loop that increments a variable (i) and then the other variables are calculated using modulo (i % 3 etc). You could use a Map to store the values of the variables indirectly, if there are a varying number of variables.
You have to create array of loop counters and increment it manually.
Quick and dirty example:
public static void nestedFors(int n, int size) {
assert n > size;
assert size > 0;
int[] i = new int[n];
int l = n - 1;
while(l >= 0) {
if(l == n - 1) {
System.out.println(Arrays.toString(i));
}
i[l]++;
if(i[l] == size - l) {
i[l] = 0;
l--;
} else if(l < n - 1) {
l++;
}
}
}
Replace System.out.println(Arrays.toString(i)) with your own code.
You can check it here: http://ideone.com/IKbDUV
It's a bit convoluted, but: here is a way to do it without recursion, in one function and without ifs.
public static void no_ifs_no_recursion(int n){
int[] helper = new int[n-1];
int[] pointers = new int[n]; //helper for printing the results
int totalsize = 1;
for (int loops = 2; loops <= n; loops++){
helper[n - loops] = totalsize;
totalsize*=loops;
}
for (int i=0; i<totalsize; i++){
int carry = i;
for (int loops = 0; loops < n-1; loops++){
pointers[loops] = carry/helper[loops];
carry = carry - (pointers[loops]*helper[loops]);
}
System.out.println(Arrays.toString(pointers));
//or do something else with `i` -> `pointers[0]`, `j` -> `pointers[1]`, `k` -> `pointers[2]` etc..
}
}
I think you need a backtracking algorithm.
But then you would replace your nested loops with recursion.
I don't want to post links here as seems moderators don't like that.
Look at "eight queens puzzle" (you can Google it), you will get my idea.
I know this idea works as I've posed this same question (which you have) to myself on many occasions, and I've applied it several times successfully.
Here is a small example (I changed it as the previous one was a bit complex).
public class Test001 {
public static void main(String[] args) {
loop(0, 5, 10);
}
/**
* max_level - the max count of nesting loops
* size - the size of the collection
*
* 0 - top most level
* level 1 - nested into 0
* level 2 - nested into 1
* ...
* and so on.
*/
private static void loop(int level, int max_level, int size){
if (level > max_level) return;
for (int i=0; i<size-level; i++){
System.out.println("Now at level: " + level + " counter = " + i);
loop(level + 1, max_level, size);
}
}
}
But this still uses recursion.