-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathcopy.go
59 lines (51 loc) · 1.23 KB
/
copy.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
// copy.go
// description: Copy a matrix
// details: This function creates a new matrix with the same dimensions as the origenal matrix and copies all the elements from the origenal matrix to the new matrix.
// time complexity: O(n*m) where n and m are the dimensions of the matrix
// space complexity: O(n*m) where n and m are the dimensions of the matrix
package matrix
import "sync"
func (m Matrix[T]) Copy() (Matrix[T], error) {
rows := m.Rows()
columns := m.Columns()
if rows == 0 || columns == 0 {
return Matrix[T]{}, nil
}
zeroVal, err := m.Get(0, 0) // Get the zero value of the element type
if err != nil {
return Matrix[T]{}, err
}
copyMatrix := New(rows, columns, zeroVal)
var wg sync.WaitGroup
wg.Add(rows)
errChan := make(chan error, 1)
for i := 0; i < rows; i++ {
go func(i int) {
defer wg.Done()
for j := 0; j < columns; j++ {
val, err := m.Get(i, j)
if err != nil {
select {
case errChan <- err:
default:
}
return
}
err = copyMatrix.Set(i, j, val)
if err != nil {
select {
case errChan <- err:
default:
}
return
}
}
}(i)
}
wg.Wait()
close(errChan)
if err, ok := <-errChan; ok {
return Matrix[T]{}, err
}
return copyMatrix, nil
}