Skip to content

Commit a9fdfe5

Browse files
committed
Add RandomizedMatrixVerifier and test class
1 parent ae71861 commit a9fdfe5

File tree

2 files changed

+113
-0
lines changed

2 files changed

+113
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* Randomized algorithm to verify if A * B = C without computing full multiplication.
3+
* Returns true if probably correct, false if definitely incorrect.
4+
* Uses Freivalds' algorithm.
5+
*/
6+
7+
package com.thealgorithms.matrix;
8+
9+
public class RandomizedMatrixVerifier {
10+
11+
public static boolean verify(int[][] A, int[][] B, int[][] C) {
12+
int n = A.length;
13+
int[] r = new int[n];
14+
15+
// Generate random vector r
16+
for (int i = 0; i < n; i++) {
17+
r[i] = (int) (Math.random() * 10); // keep it simple
18+
}
19+
20+
// Compute B * r
21+
int[] Br = new int[n];
22+
for (int i = 0; i < n; i++) {
23+
Br[i] = 0;
24+
for (int j = 0; j < n; j++) {
25+
Br[i] += B[i][j] * r[j];
26+
}
27+
}
28+
29+
// Compute A * (B * r)
30+
int[] ABr = new int[n];
31+
for (int i = 0; i < n; i++) {
32+
ABr[i] = 0;
33+
for (int j = 0; j < n; j++) {
34+
ABr[i] += A[i][j] * Br[j];
35+
}
36+
}
37+
38+
// Compute C * r
39+
int[] Cr = new int[n];
40+
for (int i = 0; i < n; i++) {
41+
Cr[i] = 0;
42+
for (int j = 0; j < n; j++) {
43+
Cr[i] += C[i][j] * r[j];
44+
}
45+
}
46+
47+
// Compare ABr and Cr
48+
for (int i = 0; i < n; i++) {
49+
if (ABr[i] != Cr[i]) return false;
50+
}
51+
52+
return true; // probably correct
53+
}
54+
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.thealgorithms.matrix;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
import org.junit.jupiter.api.Test;
5+
6+
public class RandomizedMatrixVerifierTest {
7+
8+
@Test
9+
public void testCorrectMultiplication() {
10+
int[][] A = {
11+
{1, 2},
12+
{3, 4}
13+
};
14+
int[][] B = {
15+
{5, 6},
16+
{7, 8}
17+
};
18+
int[][] C = {
19+
{19, 22},
20+
{43, 50}
21+
};
22+
23+
// Run multiple times to reduce chance of false positive
24+
boolean result = true;
25+
for (int i = 0; i < 5; i++) {
26+
if (!RandomizedMatrixVerifier.verify(A, B, C)) {
27+
result = false;
28+
break;
29+
}
30+
}
31+
assertTrue(result, "Verification should return true for correct C = A * B");
32+
}
33+
34+
@Test
35+
public void testIncorrectMultiplication() {
36+
int[][] A = {
37+
{1, 2},
38+
{3, 4}
39+
};
40+
int[][] B = {
41+
{5, 6},
42+
{7, 8}
43+
};
44+
int[][] wrongC = {
45+
{19, 22},
46+
{43, 51} // incorrect value
47+
};
48+
49+
// Even with randomness, wrong matrix should fail at least once in 5 tries
50+
boolean result = true;
51+
for (int i = 0; i < 5; i++) {
52+
if (!RandomizedMatrixVerifier.verify(A, B, wrongC)) {
53+
result = false;
54+
break;
55+
}
56+
}
57+
assertFalse(result, "Verification should return false for incorrect C");
58+
}
59+
}

0 commit comments

Comments
 (0)