forked from wncc/Hello-Foss-PyThread.cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbroadcast.cpp
60 lines (52 loc) · 1.45 KB
/
broadcast.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <omp.h>
#include <iostream>
#include <stdexcept>
#include <vector>
// Function to broadcast two matrices
void broadcast(const std::vector<std::vector<int>>& A,
std::vector<std::vector<int>>& B) {
size_t rowsA = A.size();
size_t colsA = A[0].size();
size_t rowsB = B.size();
size_t colsB = B[0].size();
if (rowsA == 0 || colsA == 0 || rowsB == 0 || colsB == 0) {
throw std::invalid_argument("Empty matrix cannot be broadcasted");
}
if (rowsA != rowsB && rowsB != 1) {
throw std::invalid_argument("Incompatible dimensions for broadcasting");
}
if (colsA != colsB && colsB != 1) {
throw std::invalid_argument("Incompatible dimensions for broadcasting");
}
if (rowsB == 1) {
B.resize(rowsA, B[0]);
}
if (colsB == 1) {
for (auto& row : B) {
row.resize(colsA, row[0]);
}
}
#pragma omp parallel for
for (size_t i = 0; i < rowsA; i++) {
#pragma omp parallel for
for (size_t j = 0; j < colsA; j++) {
B[i][j] = A[i][j] + B[i][j];
}
}
}
int main() {
std::vector<std::vector<int>> A = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
std::vector<std::vector<int>> B = {{1, 2, 3}}; // B has only one row
try {
broadcast(A, B);
for (const auto& row : B) {
for (const auto& elem : row) {
std::cout << elem << " ";
}
std::cout << std::endl;
}
} catch (const std::invalid_argument& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}