Skip to content

Commit aa709b7

Browse files
committed
feat: Add main method with demonstration example
1 parent 1fc0a95 commit aa709b7

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

src/main/java/com/thealgorithms/matrix/LUDecomposition.java

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,79 @@ public static Result decompose(double[][] matrix) {
7474
return new Result(l, u);
7575
}
7676

77+
/**
78+
* Main method for demonstration.
79+
*
80+
* @param args command line arguments (not used)
81+
*/
82+
public static void main(String[] args) {
83+
// Example from the issue
84+
double[][] matrix = {
85+
{2, -1, -2},
86+
{-4, 6, 3},
87+
{-4, -2, 8}
88+
};
89+
90+
System.out.println("LU Decomposition Example");
91+
System.out.println("========================\n");
92+
93+
Result result = decompose(matrix);
94+
95+
System.out.println("Original Matrix A:");
96+
printMatrix(matrix);
97+
98+
System.out.println("\nLower Triangular Matrix L:");
99+
printMatrix(result.getL());
100+
101+
System.out.println("\nUpper Triangular Matrix U:");
102+
printMatrix(result.getU());
103+
104+
// Verify that L * U = A
105+
System.out.println("\nVerification: L * U = A");
106+
double[][] product = multiplyMatrices(result.getL(), result.getU());
107+
printMatrix(product);
108+
}
109+
110+
/**
111+
* Helper method to print a matrix.
112+
*
113+
* @param matrix the matrix to print
114+
*/
115+
private static void printMatrix(double[][] matrix) {
116+
for (double[] row : matrix) {
117+
System.out.print("{ ");
118+
for (int i = 0; i < row.length; i++) {
119+
System.out.printf("%.3f", row[i]);
120+
if (i < row.length - 1) {
121+
System.out.print(", ");
122+
}
123+
}
124+
System.out.println(" }");
125+
}
126+
}
127+
128+
/**
129+
* Helper method to multiply two matrices.
130+
*
131+
* @param a first matrix
132+
* @param b second matrix
133+
* @return the product matrix
134+
*/
135+
private static double[][] multiplyMatrices(double[][] a, double[][] b) {
136+
int n = a.length;
137+
double[][] result = new double[n][n];
138+
139+
for (int i = 0; i < n; i++) {
140+
for (int j = 0; j < n; j++) {
141+
for (int k = 0; k < n; k++) {
142+
result[i][j] += a[i][k] * b[k][j];
143+
}
144+
}
145+
}
146+
147+
return result;
148+
}
149+
77150
/**
78151
* Result class to hold L and U matrices from decomposition.
79152
*/

0 commit comments

Comments
 (0)