This code is supposed to multiply two matrices which it does. This was for a homework assignment that I got 100 on it because my buddy helped me out.
But I'm trying to actually understand how it works and I keep getting confused for some reason. I don't really understand what the third for loop is doing.
int mA = matrix1.length;
int nA = matrix1[0].length;
int mB = matrix2.length;
int nB = matrix2[0].length;
if (nA != mB){
return null;
double[][] C = new double[mA][nB];
for (int i = 0; i < mA; i++)
for (int j = 0; j < nB; j++)
for (int k = 0; k < nA; k++)
C[i][j] += matrix1[i][k] * matrix2[k][j];
return C;
You are implementing matrix multiplication.
You can find a good explanation on Java With Us
Related
Actually the following code is doing the gaussian elimination for a matrix. And my job is to try some java concurrency technique to let it be a parallel program.
However, the problem is that each external loop has the data dependency which comes from the previous loop. And I have try that it is too costly to use the parallel technique inside the external loop. Can someone help me with it? How to let the following code run by parallel? Is there any technique in java concurrency technique can handle with this condition?
for (int i = 0; i <1; i++) {
int max = i;
for (int j = i + 1; j < N; j++) {
if (Math.abs(matrix[j][i]) > Math.abs(matrix[max][i])) {
max = j;
}
}
double[] temp = matrix[i];
matrix[i] = matrix[max];
matrix[max] = temp;
for (int k = i + 1; k < N; k++)
{
double alpha = matrix[k][i] / matrix[i][i];
for (int j = i; j < N; j++)
{
matrix[k][j] -= alpha * matrix[i][j];
}
}
}
The work done by the k loop can be made parallel, since the modified data is non-overlapping.
Simply delegate the work done by the body of the loop to a thread.
Easiest way is to use a Java 8 parallel stream, i.e. replace the k loop with:
final int ii = i; // since 'i' is not effectively-final
IntStream.range(ii + 1, N).parallel().forEach(k -> {
double alpha = matrix[k][ii] / matrix[ii][ii];
for (int j = ii; j < N; j++) {
matrix[k][j] -= alpha * matrix[ii][j];
}
});
I'm trying to formulate a VRPTW model in Java, same one in OPL works just fine, but I keep getting problem with one constrain:
a[i][k]+t[i][j]- a[j][k] + M * x[i][j][k] = M
I get error mesagge: The method addTerm(double, IloNumVar) in the type IloLinearNumExpr is not applicable for the arguments (double).
It seams that it is a problem only with t[i][j] which is double and calculated based on two other doubles: t[i][j] = d[i][j]+ s[i];
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
for(int k = 0; k < v; k++) {
if(i != j) {
IloLinearNumExpr expr8 = cplex.linearNumExpr();
expr8.addTerm(1.0, a[i][k]);
expr8.addTerm(t[i][j]);
expr8.addTerm(-1.0, a[j][k]);
expr8.addTerm(M, x[i][j][k]);
cplex.addLe(expr8, M);
Any ideas are welcome.
Thank you!
You should use setConstant:
expr8.setConstant(t[i][j]);
I am working on the LeetCode question Longest Substring Without Repeating Characters. But I got two different results between Run Code and Submit Solution. My c++ code is
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int* a = new int[257];
int ans = 0;
int n = s.size();
for (int j = 0, i = 0; j < n; j++) {
i = i > a[s[j]] ? i : a[s[j]];
ans = ans > j - i +1 ? ans : j - i + 1;
a[s[j]] = j + 1;
}
return ans;
}
};
And two outputs are
I don't know what's wrong with my code. Besides, my c++ code is written by learning his website java answer
public class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length(), ans = 0;
int[] index = new int[128]; // current index of character
// try to extend the range [i, j]
for (int j = 0, i = 0; j < n; j++) {
i = Math.max(index[s.charAt(j)], i);
ans = Math.max(ans, j - i + 1);
index[s.charAt(j)] = j + 1;
}
return ans;
}
}
for (int j = 0, i = 0; j < n; j++) {
i = i > a[s[j]] ? i : a[s[j]];
Since a is uninitialized, a[s[j]] is undefined behavior. You want
for (int i=0;i<257;i++)
a[i]=0;
or better a vector
vector<int> a(257,0);
Unlike Java, C++ does not zero heap memory for you.
int* a = new int[257];
What is the data inside your array a?
In Java, a[0], a[1], ... a[256] are all equal to zero. But in C++, a[0], a[1], ... a[256] contains random garbage from whatever data was previously at that memory address.
You have to zero the memory first:
std::fill_n(a, 257, 0);
Or, if you prefer memset:
std::memset(a, 0, sizeof(int) * 257);
EDIT: As pointed out by #It'scominghome, value-initialization (C++11) is also possible:
int* a = new int[257](); // will zero the array
I'm sure the answer is fairly simple, but I'm not getting it. Here we go with my example:
int matrix [][] = new int [rows][columns];
for (int i = 0; i < matrix.length; i++)
{
for(int j = 0; j < matrix[0].length; j++)
{
mata[i][j] = Integer.parseInt (args[j]);
}
}
How can I make j count further upwards after the programm goes from the inner loop to the outer loop and back to the inner one? Usually, it would start from zero again, which is not intended, as I need the next command line argument. I tried a few things, can't get it to work, though.
You can add an outer variable:
int k = 0;
then replace the innermost line by:
mata[i][j] = Integer.parseInt(args[k]);
k += 1;
Or compute it:
mata[i][j] = Integer.parseInt(args[i * matrix.length + j]);
Just use a separate variable (argc below):
int matrix[][] = new int[rows][columns];
for (int i = 0, argc = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++, argc++) {
mata[i][j] = Integer.parseInt(args[argc]);
}
}
I am having a really hard time creating a method to raise a matrix to the power. I tried using this
public static int powerMethod(int matrix, int power) {
int temp = matrix ;
for (int i = power; i == 1; i--)
temp = temp * matrix ;
return temp ;
but the return is WAYYY off. Only the first (1,1) matrix element is on point.
I tried using that method in a main like so
// Multiplying matrices
for (i = 0; i < row; i++)
{
for (j = 0; j < column; j++)
{
for (l = 0; l < row; l++)
{
sum += matrix[i][l] * matrix[l][j] ;
}
matrix[i][j] = sum ;
sum = 0 ;
}
}
// Solving Power of matrix
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++)
matrixFinal[power][i][j] = Tools.powerMethod(matrix[i][j], power) ;
}
Where "power", "row", and "column" is an int that the user enters.
Any ideas how I can do this??
Thanks!!!
You have a lot of issues here.
First, your matrix squaring algorithm has a (common) error. You have:
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++) {
for (l = 0; l < row; l++) {
sum += matrix[i][l] * matrix[l][j] ;
}
matrix[i][j] = sum ;
sum = 0 ;
}
}
However, you need to store the result in a temporary second matrix, because when you do matrix[i][j] = sum, it replaces the value at that position with the output, then later results end up being incorrect. Also I suggest initializing sum to 0 first, since it appears you declare it outside of this loop, and initializing it first protects you against any arbitrary value sum may have before going into the loop. Furthermore, it is not immediately clear what you mean by row and column -- make sure you are iterating over the entire matrix. E.g.:
int temp[][] = new int[matrix.length];
for (i = 0; i < matrix.length; i++) {
temp[i] = new int[matrix[i].length];
for (j = 0; j < matrix[i].length; j++) {
sum = 0 ;
for (l = 0; l < matrix.length; l++) {
sum += matrix[i][l] * matrix[l][j] ;
}
temp[i][j] = sum ;
}
}
// the result is now in 'temp', you could do this if you wanted:
matrix = temp;
Note that matrix.length and matrix[i].length are fairly interchangeable above if the matrix is square (which it must be, in order to be multiplied by itself).
Secondly, your multiplication squares a matrix. This means if you repeatedly apply it, you keep squaring the matrix every time, which means you will only be able to compute powers that are themselves powers of two.
Your third issue is your final bit doesn't make much sense:
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++)
matrixFinal[power][i][j] = Tools.powerMethod(matrix[i][j], power) ;
}
It's not immediately clear what you are trying to do here. The final part seems to be trying to raise individual elements to a certain power. But this is not the same as raising a matrix to a power.
What you need to do is define a proper matrix multiplication method that can multiply two arbitrary matrices, e.g.:
int[][] multiplyMatrices (int[][] a, int[][] b) {
// compute and return a x b, similar to your existing multiplication
// algorithm, and of course taking into account the comments about
// the 'temp' output matrix above
}
Then computing a power becomes straightforward:
int[][] powerMatrix (int[][] a, int p) {
int[][] result = a;
for (int n = 1; n < p; ++ n)
result = multiplyMatrices(result, a);
return result;
}
Why not just use Math.pow?
import java.lang.Math;
Then you just have to do
matrixFinal[power][i][j] = (int) Math.pow(matrix[i][j],power); //might have to cast this to an int