-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathadd.go
69 lines (58 loc) · 1.39 KB
/
add.go
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
61
62
63
64
65
66
67
68
69
// add.go
// description: Add two matrices
// time complexity: O(n^2)
// space complexity: O(n^2)
package matrix
import (
"context"
"errors"
"sync"
)
// Add adds two matrices.
func (m1 Matrix[T]) Add(m2 Matrix[T]) (Matrix[T], error) {
// Check if the matrices have the same dimensions.
if !m1.MatchDimensions(m2) {
return Matrix[T]{}, errors.New("matrices are not compatible for addition")
}
// Create a new matrix to store the result.
var zeroVal T
result := New(m1.Rows(), m1.Columns(), zeroVal)
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // Make sure it's called to release resources even if no errors
var wg sync.WaitGroup
errCh := make(chan error, 1)
for i := 0; i < m1.rows; i++ {
i := i // Capture the loop variable for the goroutine
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < m1.columns; j++ {
select {
case <-ctx.Done():
return // Context canceled; return without an error
default:
}
sum := m1.elements[i][j] + m2.elements[i][j]
err := result.Set(i, j, sum)
if err != nil {
cancel() // Cancel the context on error
select {
case errCh <- err:
default:
}
return
}
}
}()
}
// Wait for all goroutines to finish
go func() {
wg.Wait()
close(errCh)
}()
// Check for any errors
if err := <-errCh; err != nil {
return Matrix[T]{}, err
}
return result, nil
}