Skip to content

Add RandomizedMatrixVerifier and test class #6305

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/**
* Randomized algorithm to verify if A * B = C without computing full multiplication.
* Returns true if probably correct, false if definitely incorrect.
* Uses Freivalds' algorithm.
*/

package com.thealgorithms.matrix;

public class RandomizedMatrixVerifier {

public static boolean verify(int[][] A, int[][] B, int[][] C) {
int n = A.length;
int[] r = new int[n];

// Generate random vector r
for (int i = 0; i < n; i++) {
r[i] = (int) (Math.random() * 10); // keep it simple
}

// Compute B * r
int[] Br = new int[n];
for (int i = 0; i < n; i++) {
Br[i] = 0;
for (int j = 0; j < n; j++) {
Br[i] += B[i][j] * r[j];
}
}

// Compute A * (B * r)
int[] ABr = new int[n];
for (int i = 0; i < n; i++) {
ABr[i] = 0;
for (int j = 0; j < n; j++) {
ABr[i] += A[i][j] * Br[j];
}
}

// Compute C * r
int[] Cr = new int[n];
for (int i = 0; i < n; i++) {
Cr[i] = 0;
for (int j = 0; j < n; j++) {
Cr[i] += C[i][j] * r[j];
}
}

// Compare ABr and Cr
for (int i = 0; i < n; i++) {
if (ABr[i] != Cr[i]) return false;
}

return true; // probably correct
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.thealgorithms.matrix;

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class RandomizedMatrixVerifierTest {

@Test
public void testCorrectMultiplication() {
int[][] A = {
{1, 2},
{3, 4}
};
int[][] B = {
{5, 6},
{7, 8}
};
int[][] C = {
{19, 22},
{43, 50}
};

// Run multiple times to reduce chance of false positive
boolean result = true;
for (int i = 0; i < 5; i++) {
if (!RandomizedMatrixVerifier.verify(A, B, C)) {
result = false;
break;
}
}
assertTrue(result, "Verification should return true for correct C = A * B");
}

@Test
public void testIncorrectMultiplication() {
int[][] A = {
{1, 2},
{3, 4}
};
int[][] B = {
{5, 6},
{7, 8}
};
int[][] wrongC = {
{19, 22},
{43, 51} // incorrect value
};

// Even with randomness, wrong matrix should fail at least once in 5 tries
boolean result = true;
for (int i = 0; i < 5; i++) {
if (!RandomizedMatrixVerifier.verify(A, B, wrongC)) {
result = false;
break;
}
}
assertFalse(result, "Verification should return false for incorrect C");
}
}
Loading