I'm currently working on implementing the Floyd Warshall algorithm from pseudocode to java. I felt like I had it correct, but anytime I ran it on a graph, I was getting an output of large negative number and I feel that it was probably the way I implemented my algorithm. After looking I realized I may have missed something. I haven't implemented the k-1 part of the pseudocode and I'm not sure how to implement this. Im hoping this will correct the issue.
Here it the code i have written.
public static int[][] floyd(int n, int[][] W, int[][] P, int[][] D) {
D = W;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
P[i][j] = 0;
for (int k = 0; k < n; k++)
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
if ((D[i][j] == Integer.MAX_VALUE) && (D[i][k] + D[k][j] == Integer.MAX_VALUE)) { // add
continue;
} else if (D[i][j] <= D[i][k] + D[k][j]) {
D[i][j] = D[i][j];
} else {
D[i][j] = D[i][k] + D[k][j];
}
}
return D;
}
And here is the pseudocode im writing based off of.
Floyd-Warshall(W)
n = W.rows
D(0) = W
for (k = 1 to n)
for ( i = 1 to n )
for ( j = 1 to n )
if (dij(k-1) == INF) && (dik(k-1) + dkj(k-1)) == INF)
continue
else if (dij(k-1) ≤ dik(k-1) + dkj(k-1))
dij(k) = dij(k-1) // add
else
dij(k) = dik(k-1) + dkj(k-1) // add
return (D(n))
EDIT
Heres all of my code thats relevant with some corrections
int V = g.nodeList.size();
int W[][] = new int[V][V];
int P[][] = new int[V][V];
// Adding wights to graph
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
W[j][i] = Integer.parseInt(g.edgeList.get((j * V) + i).label);
if (W[j][i] == 0) {
W[i][j] = Integer.MAX_VALUE;
}
}
}
System.out.println("Matrix to find the shortest path of.");
printMatrix(W, V, g);
System.out.println("Shortest Path Matrix.");
printMatrix(floyd(V, W, P), V, g);
System.out.println("Path Matrix");
printPredMatrix(P, V, g);
}
public static int[][] floyd(int n, int[][] W, int[][] P) {
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
P[i][j] = 0;
for (int k = 0; k < n; k++)
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
if ((W[i][j] == Integer.MAX_VALUE) && (W[i][k] + W[k][j] == Integer.MAX_VALUE)) { // add
continue;
} else if (W[i][j] <= W[i][k] + W[k][j]) {
W[i][j] = W[i][j];
} else {
W[i][j] = W[i][k] + W[k][j];
}
}
return W;
}
public static int min(int i, int j) {
if (i > j) {
return j;
}
return i;
}
public static void printMatrix(int[][] Matrix, int V, Graph g) {
System.out.print("\n\t");
for (int j = 0; j < V; j++) {
System.out.print(g.nodeList.get(j).name + "\t");
}
System.out.println();
for (int j = 0; j < 35; j++) {
System.out.print("-");
}
System.out.println();
for (int i = 0; i < V; i++) {
System.out.print(g.nodeList.get(i).name + " |\t");
for (int j = 0; j < V; j++) {
if ((Matrix[i][j] == Integer.MAX_VALUE)||(Matrix[i][j] == Integer.MIN_VALUE)) {
System.out.print("~");
} else {
System.out.print(Matrix[i][j]);
}
System.out.print("\t");
}
System.out.println("\n");
}
System.out.println("\n");
}
public static void printPredMatrix(int[][] Matrix, int V, Graph g) {
System.out.print("\n\t");
for (int j = 0; j < V; j++) {
System.out.print(g.nodeList.get(j).name + "\t");
}
System.out.println();
for (int j = 0; j < V * 3; j++) {
System.out.print("-");
}
System.out.println();
for (int i = 0; i < V; i++) {
System.out.print(g.nodeList.get(i).name + " |\t");
for (int j = 0; j < V; j++) {
System.out.print(Matrix[i][j]);
System.out.print("\t");
}
System.out.println("\n");
}
System.out.println("\n");
}
}```
Related
For my university assignment in java I have been asked to provide "extra analytics functions" I decided to use Levenshtein distance but I have an issue where the number outputted to the console is one less than the actual answer. So the distance between "cat" and "hat" should be 1 but it's displaying as 0
public class Levenshtein {
public Levenshtein(String first, String second) {
char [] s = first.toCharArray();
char [] t = second .toCharArray();
int Subcost = 0;
int[][] array = new int[first.length()][second.length()];
for (int i = 0; i < array[0].length; i++)
{
array[0][i] = i;
}
for (int j = 0; j < array.length; j++)
{
array [j][0]= j;
}
for (int i = 1; i < second.length(); i++)
{
for (int j = 1; j < first.length(); j++)
{
if (s[j] == t [i])
{
Subcost = 0;
}
else
{
Subcost = 1;
}
array [j][i] = Math.min(array [j-1][i] +1,
Math.min(array [j][i-1] +1,
array [j-1][i-1] + Subcost) );
}
}
UI.output("The Levenshtein distance is -> " + array[first.length()-1][second.length()-1]);
}
}
Apparently you're using the following algorithm:
https://en.wikipedia.org/wiki/Levenshtein_distance#Iterative_with_full_matrix
I think you were not too accurate with indices. I'm not sure where exactly the problem is, but here is a working version:
public int calculateLevenshteinDistance(String first, String second) {
char[] s = first.toCharArray();
char[] t = second.toCharArray();
int substitutionCost = 0;
int m = first.length();
int n = second.length();
int[][] array = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++) {
array[i][0] = i;
}
for (int j = 1; j <= n; j++) {
array[0][j] = j;
}
for (int j = 1; j <= n; j++) {
for (int i = 1; i <= m; i++) {
if (s[i - 1] == t[j - 1]) {
substitutionCost = 0;
} else {
substitutionCost = 1;
}
int deletion = array[i - 1][j] + 1;
int insertion = array[i][j - 1] + 1;
int substitution = array[i - 1][j - 1] + substitutionCost;
int cost = Math.min(
deletion,
Math.min(
insertion,
substitution));
array[i][j] = cost;
}
}
return array[m][n];
}
In this method only one element is getting sorted rest of the elements are are not sorted.
Please help me to find where the actual problem is
private static int[] selectSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int min_Ele = i;
for (int j = 1; j < n; j++) {
if (arr[j] <= arr[min_Ele]) {
min_Ele = j;
}
}
if (i != min_Ele) {
int tmp = arr[i];
arr[i] = arr[i = min_Ele];
arr[min_Ele] = tmp;
}
}
return arr;
}
Your mistake is that your inner loop should start from i+1 and not from 1.
public static int[] selectSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int min_Ele = i;
for (int j = i+1; j < n; j++) {
if (arr[j] <= arr[min_Ele]) {
min_Ele = j;
}
}
if (i != min_Ele){
//swap
int tmp = arr[i];
arr[i] = arr[i = min_Ele];
arr[min_Ele] = tmp;
}
return arr;
}
private static int[] selectSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n-1; i++) {
int min_Ele = i;
for (int j = i+1; j < n; j++) {
if (arr[j] <= arr[min_Ele]) {
min_Ele = j;
}
}
if (i != min_Ele) {
int tmp = arr[i];
arr[i] = arr[min_Ele];
arr[min_Ele] = tmp;
}
}
return arr;
}
I need help making a mirrored triangle like this:
* *
** **
*** ***
********
I can get each one seperatly, but I can't combine them.
public static void main(String[] args){
for( int i = 1; i <= 5; i++ ){
for( int j = 0; j < i; j++ ){
System.out.print("*");
}
System.out.println();
}
for(int i = 0; i < 6; i++)
{
for(int j = 5; j > 0; j--)
{
if(i < j)
System.out.print(" ");
else
System.out.print("*");
}
System.out.println();
}
}
You need to track the position from both sides to be able to show * at correct location. Here is the solution:
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 10; j++) {
if (j <= i || j > 10 - i) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
You can do it using this code.
public class Test {
public void sizeOfTri(int triSize) { //Number of lines
int line = 1;
for(int i = 0; i < triSize; i++) { //Handles Each line
int temp = triSize * 2;
for(int j = 1; j < temp; j++) { //Handles Each space on the line
if(j <= line && j == triSize || j >= temp - line && j == triSize) { //For the very last line because it needs an extra *
System.out.print("**");
} else if(j <= line || j >= temp - line) { //For normal lines
System.out.print("*");
} else if(j == triSize) {
System.out.print(" "); //For the second to last line because it needs an extra space to make it look mirrored
} else { //For normal lines
System.out.print(" ");
}
}
System.out.println();
line++;
}
}
public static void main(String[] args) {
new Test().sizeOfTri(4);
}
}
I commented on next to if statements on which part does what. This will produce an output which looks like the below when run
* *
** **
*** ***
********
Although, all the above implementations are really good ones. I thought of doing it bit differently and make use of 2-D arrays.
package algorithms;
public class DrawMirror {
static void initialize(String[][] array){
for (int i=0; i<MAX_X; i++){
for (int j=0; j < MAX_Y; j++){
array[i][j] = " ";
}
}
}
static void draw(String[][] array, int x, int y){
for (int i=0; i < y; i++){
array[x][i] = "*";
array[x][MAX_Y-i-1] = "*";
}
}
final static int MAX_X = 4;
final static int MAX_Y = 8;
public static void main(String[] args) {
String[][] array = new String[MAX_X][MAX_Y];
initialize(array);
for (int i=0; i < MAX_X ; i++){
draw(array,i,i+1);
}
for( int i = 0; i < MAX_X; i++ ){
for( int j = 0; j < MAX_Y; j++ ){
System.out.print(array[i][j]);
}
System.out.println();
}
}
}
The following code is a function with variable height.
public static void printDoubleTriangle(int height) {
for(int i = 0; i < height; i++) {
for(int j = 0; j < 2*height; j++) {
if(j <= i || (2*height - j - 1) <= i) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
I am getting an index out of bound error for this.
I set on netbeans the argument on the project and works fine.
But how can i set an argument for n within the code without going on the project properties and changing the value there?
When i try to put static int N = 4 ; i get error throughout code, can someone help me please?
package matrix;
// performing matrix multiplication parallely by using two threads
// In thread 1 we will multiply matrix a and b and store in C with range of 0 to N/2
// In thread 2 we will multiply matrix a and b and store in C with range of N/2 to N
// For our convenience I'm used 4 instead of N ( we can replace 4 with N)
public class Mymainclass implements Runnable {
static int n;
// a and b are input matrix's
static int a[][];
static int b[][];
/* we will multiply the elements in a and b matrix's
* parallely by using two threads
and will store in the c matrix sequentially.*/
static int c[][];
public Mymainclass(int n1) {
n = n1;
a = new int[n][n];
b = new int[n][n];
c = new int[n][n];
}
public void run() {
int i, j, k;
System.out.println("in thread1 class");
for (i = 0; i < this.n; i++) {
for (j = 0; j < n; j++) {
for (k = 0; k < n; k++) {
this.c[i][j] += a[i][k] * b[k][j];
}
}
}
System.out.print("\n");
System.out.println("Matrix c in thread1");
for (int a = 0; a < n; a++) {
for (int b = 0; b < n; b++) {
System.out.print(c[a][b] + " ");
}
System.out.print("\n");
}
}
public static void main(String[] args) {
String n1 = args[0];
n = Integer.parseInt(n1);
System.out.println(n);
Mymainclass th1 = new Mymainclass(n);
int z = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = z++;
}
System.out.print("\n");
}
z = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
b[i][j] = z++;
}
System.out.print("\n");
}
System.out.println("Matrix a");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print("\n");
}
System.out.print("\n");
System.out.println("Matrix b");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(b[i][j] + " ");
}
System.out.print("\n");
}
System.out.print("\n");
Thread t = new Thread(th1);
t.start();
}
}
That is working for me:
public class Mymainclass implements Runnable {
static int n;
// a and b are input matrix's
static int a[][];
static int b[][];
/* we will multiply the elements in a and b matrix's
* parallely by using two threads
and will store in the c matrix sequentially.*/
static int c[][];
public Mymainclass(int n1) {
n = n1;
a = new int[n][n];
b = new int[n][n];
c = new int[n][n];
}
public void run() {
int i, j, k;
System.out.println("in thread1 class");
for (i = 0; i < this.n; i++) {
for (j = 0; j < n; j++) {
for (k = 0; k < n; k++) {
this.c[i][j] += a[i][k] * b[k][j];
}
}
}
System.out.print("\n");
System.out.println("Matrix c in thread1");
for (int a = 0; a < n; a++) {
for (int b = 0; b < n; b++) {
System.out.print(c[a][b] + " ");
}
System.out.print("\n");
}
}
static int N = 4 ;
public static void main(String[] args) {
Mymainclass th1 = new Mymainclass(N);
int z = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = z++;
}
System.out.print("\n");
}
z = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
b[i][j] = z++;
}
System.out.print("\n");
}
System.out.println("Matrix a");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print("\n");
}
System.out.print("\n");
System.out.println("Matrix b");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(b[i][j] + " ");
}
System.out.print("\n");
}
System.out.print("\n");
Thread t = new Thread(th1);
t.start();
}
}
For measuring time just change code where you start thread to:
ExecutorService service = Executors.newSingleThreadExecutor();
long start = System.currentTimeMillis();
Future<?> future = service.submit(th1);
try {
future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("time: " + (System.currentTimeMillis() - start));
service.shutdown();
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Hi I have the Jama librarry, but this libraray work only with Double numbers..and its very slow. for Android app ..and finally i dont need so high precision of eig decomp..so is there some JAva libaray with float num.....similar in syntax with jama? becouse...I dont want to re-- write again my 440 rows code thanks. eig. Transpose, inverse and so basic Linear algebra operations..
or exist same java library eigenvalues. with threads?
I know of one library called la4j, you might be interested in looking into that. I should mention that, generally, I don't think Java is a good choice if you're planning on doing many matrix manipulations/calculations (I myself have tried and hit a dead-end), you might be better off looking into Python (NumPy) or C++ (Armadillo) for such projects.
Or are you looking for something like this?
import java.util.Arrays;
public class Matrix {
protected int rows;
protected int cols;
double[][] values;
public Matrix(int rows, int cols) {
this.rows = rows;
this.cols = cols;
values = new double[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
values[i][j] = 0;
}
public Matrix(int[][] M) {
this.rows = M.length;
this.cols = M[0].length;
values = new double[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
values[i][j] = M[i][j];
}
public Matrix(double[][] M) {
this.rows = M.length;
this.cols = M[0].length;
values = new double[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
values[i][j] = M[i][j];
}
public void setToEye() {
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
values[i][j] = (i == j) ? 1 : 0;
}
public static int[] matrixSize(Matrix M) {
int[] size = new int[2];
size[0] = M.rows;
size[1] = M.cols;
return size;
}
public static double vectMul(double[] A, double[] B) {
double suma = 0;
for (int i = 0; i < A.length; i++)
suma += A[i] * B[i];
return suma;
}
public static Matrix matrixTranspose(Matrix M) {
int[] size = matrixSize(M);
double[][] Mt = new double[size[0]][size[1]];
for (int i = 0; i < size[0]; i++)
for (int j = 0; j < size[1]; j++)
Mt[i][j] = M.getValue(j, i);
return new Matrix(Mt);
}
public static Matrix matrixMul(Matrix A, Matrix B) {
int m1 = matrixSize(A)[0];
int n1 = matrixSize(A)[1];
int m2 = matrixSize(B)[0];
int n2 = matrixSize(B)[1];
double[][] rez;
if (n1 != m2) {
System.err.println("Inner matrix dimensions must agree!");
return null;
}
rez = new double[m1][n2];
for (int i = 0; i < m1; i++)
for (int j = 0; j < n2; j++)
rez[i][j] = vectMul(A.getRow(i), B.getColumn(j));
Matrix r = new Matrix(rez);
return r;
}
public static Matrix matrixMulWithMod(Matrix A, Matrix B, double mod) {
int m1 = matrixSize(A)[0];
int n1 = matrixSize(A)[1];
int m2 = matrixSize(B)[0];
int n2 = matrixSize(B)[1];
double[][] rez;
if (n1 != m2) {
System.err.println("Inner matrix dimensions must agree!");
return null;
}
rez = new double[m1][n2];
for (int i = 0; i < m1; i++)
for (int j = 0; j < n2; j++)
rez[i][j] = vectMul(A.getRow(i), B.getColumn(j)) % mod;
Matrix r = new Matrix(rez);
return r;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < this.rows; i++) {
sb.append(Arrays.toString(values[i]));
sb.append('\n');
}
String str = sb.toString();
return str;
}
public double[][] getValues() {
return values;
}
public void setValues(double[][] values) {
this.values = values;
}
public void setValues(int[][] values) {
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
this.values[i][j] = (double) values[i][j];
}
public double getValue(int row, int col) {
return values[row][col];
}
public void setValue(int row, int col, double value) {
values[row][col] = value;
}
public double[] getRow(int row) {
double[] temp = new double[cols];
for (int i = 0; i < temp.length; i++)
temp[i] = values[row][i];
return temp;
}
public double[] getColumn(int col) {
double[] temp = new double[rows];
for (int i = 0; i < temp.length; i++)
temp[i] = values[i][col];
return temp;
}
public double[] toDoubleArray() {
double[] temp = new double[rows * cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
temp[i * (rows + 1) + j] = values[i][j];
return temp;
}
public int[] toIntArray() {
int[] temp = new int[rows * cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
temp[i * (rows + 1) + j] = (int) values[i][j];
return temp;
}
public int getRowCount() {
return this.rows;
}
public int getColumnsCount() {
return this.cols;
}
public static double getMatrixDet(Matrix M) {
int m = M.getRowCount();
int n = M.getColumnsCount();
double D = 0;
if (m != n) {
System.err.println("Matrix must be square!");
System.exit(0);
}
if (n > 1) {
Matrix I = new Matrix(m - 1, n - 1);
for (int i = 1; i < m; i++)
for (int j = 1; j < n; j++)
I.setValue(i - 1, j - 1, M.getValue(i, j));
D = M.getValue(0, 0) * getMatrixDet(I);
} else
D = M.getValue(0, 0);
// za niz , kopira iz niza a elemente 0:i-1 i+1:n sredi za matrcu
Matrix I = new Matrix(m - 1, n - 1);
for (int i = 1; i < n; i++) {
I = M.withoutIthRowAndJthCol(i, 0);
D = D + Math.pow((-1), i) * M.getValue(i, 0) * getMatrixDet(I);
}
return D;
}
public Matrix transpose() {
Matrix temp = new Matrix(this.values);
for (int i = 0; i < this.rows; i++)
for (int j = 0; j < this.cols; j++)
this.values[i][j] = temp.getValue(j, i);
return this;
}
private Matrix withoutIthRowAndJthCol(int row, int col) {
Matrix temp = new Matrix(this.rows - 1, this.cols - 1);
int k = 0, l = 0;
for (int i = 0; i < this.getRowCount(); i++) {
if (i == row)
continue;
for (int j = 0; j < this.getColumnsCount(); j++) {
if (j == col)
continue;
temp.setValue(k, l, this.values[i][j]);
l++;
}
l %= 2;
k++;
}
return temp;
}
public static Matrix getMatrixAdj(Matrix M) {
int m = M.getRowCount();
int n = M.getColumnsCount();
Matrix A = new Matrix(m, n);
if (m != n) {
System.err.println("Matrix must be square!");
System.exit(0);
}
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
A.setValue(i, j, Math.pow((-1), i + j)
* getMatrixDet(M.withoutIthRowAndJthCol(i, j)));
}
A.transpose();
return A;
}
public static Matrix matrixDiv(Matrix M, double n) {
Matrix temp = M;
for (int i = 0; i < M.getRowCount(); i++)
for (int j = 0; j < M.getColumnsCount(); j++)
temp.setValue(i, j, (M.getValue(i, j) / n));
return temp;
}
public static Matrix getMatrixInv(Matrix M) {
Matrix I = new Matrix(M.getRowCount(), M.getColumnsCount());
if (M.getRowCount() != M.getColumnsCount()) {
System.err.println("Matrix must be square!");
System.exit(0);
}
if (getMatrixDet(M) == 0) {
System.err.println("Matrix is singular!");
System.exit(0);
}
I = matrixDiv(getMatrixAdj(M), getMatrixDet(M));
return I;
}
}
if this is what you wanted, you're welcome.