Skip to content

Commit 6fd61c2

Browse files
committed
feat(Codewars): Solve onlinePlatform/codewars/5kyu/square_matrix_multiplication.cc
1 parent d07dfdd commit 6fd61c2

File tree

3 files changed

+85
-1
lines changed

3 files changed

+85
-1
lines changed

src/onlinePlatform/codewars/5kyu/CMakeLists.txt

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,14 @@ target_link_libraries(
88
rot13GoogleTest
99
GTest::gtest_main
1010
)
11-
1211
gtest_discover_tests(rot13GoogleTest)
12+
13+
add_executable(
14+
square_matrix_multiplication_google_test
15+
square_matrix_multiplication_google_test.cc
16+
)
17+
target_link_libraries(
18+
square_matrix_multiplication_google_test
19+
GTest::gtest_main
20+
)
21+
gtest_discover_tests(square_matrix_multiplication_google_test)
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// https://www.codewars.com/kata/5263a84ffcadb968b6000513/train/cpp
2+
3+
#include <string>
4+
#include <vector>
5+
6+
std::vector<std::vector<int>>
7+
matrix_multiplication(const std::vector<std::vector<int>> &a,
8+
const std::vector<std::vector<int>> &b, size_t n) {
9+
// TODO: Return the result of A × B in the form of an n × n matrix
10+
// NOTE: Please allocate and return matrix C
11+
std::vector<std::vector<int>> c(n, std::vector<int>(n));
12+
13+
for (int i = 0; i < n; ++i) {
14+
for (int j = 0; j < n; ++j) {
15+
c[i][j] = 0;
16+
for (int k = 0; k < n; ++k) {
17+
c[i][j] += a[i][k] * b[k][j];
18+
}
19+
}
20+
}
21+
22+
return c;
23+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#include <gtest/gtest.h>
2+
#include <string>
3+
#include <vector>
4+
5+
#include "square_matrix_multiplication.cc"
6+
7+
void square_matrix_assert_eq(std::vector<std::vector<int>> &actual,
8+
std::vector<std::vector<int>> &expected, int n) {
9+
// Assert that the two matrices are equal
10+
for (int i = 0; i < n; i++) {
11+
for (int j = 0; j < n; j++) {
12+
// Assert::That(actual[i][j], Equals(expected[i][j]));
13+
EXPECT_EQ(actual[i][j], expected[i][j]);
14+
}
15+
}
16+
}
17+
18+
TEST(SquareMatrixMultiplication, should_work_for_the_example_provided_in_the_description) {
19+
std::vector<std::vector<int>> a(2, std::vector<int>(2)),
20+
b(2, std::vector<int>(2)), expected(2, std::vector<int>(2)), actual;
21+
/*
22+
1 2
23+
A =
24+
3 2
25+
*/
26+
// Assuming Row->Col, means storage is row-wise
27+
a[0][0] = 1;
28+
a[0][1] = 2;
29+
a[1][0] = 3;
30+
a[1][1] = 2;
31+
/*
32+
3 2
33+
B =
34+
1 1
35+
*/
36+
b[0][0] = 3;
37+
b[0][1] = 2;
38+
b[1][0] = 1;
39+
b[1][1] = 1;
40+
/*
41+
5 4
42+
A × B =
43+
11 8
44+
*/
45+
expected[0][0] = 5;
46+
expected[0][1] = 4;
47+
expected[1][0] = 11;
48+
expected[1][1] = 8;
49+
50+
actual = matrix_multiplication(a, b, 2);
51+
square_matrix_assert_eq(actual, expected, 2);
52+
}

0 commit comments

Comments
 (0)