Created
February 3, 2021 16:04
-
-
Save tomowarkar/962c979d52d1e9a6ccb2c7a18e0eaf66 to your computer and use it in GitHub Desktop.
Golang matrix multiplication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "reflect" | |
| "strconv" | |
| ) | |
| type matrix [][]int | |
| func (m matrix) size() (int, int) { | |
| return len(m), len(m[0]) | |
| } | |
| func (m matrix) toString() (ret string) { | |
| for i := range m { | |
| for _, a := range m[i] { | |
| ret += strconv.Itoa(a) + "\t" | |
| } | |
| ret += "\n" | |
| } | |
| return ret | |
| } | |
| func (m matrix) mul(other matrix) matrix { | |
| h, w := m.size() | |
| oh, ow := other.size() | |
| if w != oh { | |
| panic("Can't do multiplication.") | |
| } | |
| ret := make(matrix, h) | |
| for i := range ret { | |
| ret[i] = make([]int, ow) | |
| for j := range ret[i] { | |
| for k := 0; k < w; k++ { | |
| ret[i][j] += m[i][k] * other[k][j] | |
| } | |
| } | |
| } | |
| return ret | |
| } | |
| func main() { | |
| mat1 := matrix{ | |
| []int{2, 3}, | |
| []int{1, 4}, | |
| []int{2, 1}, | |
| } | |
| mat2 := matrix{ | |
| []int{3, 1, 2}, | |
| []int{2, 4, 2}, | |
| } | |
| got := mat1.mul(mat2) | |
| var expect matrix | |
| // success case (no output) | |
| expect = matrix{ | |
| []int{12, 14, 10}, | |
| []int{11, 17, 10}, | |
| []int{8, 6, 6}, | |
| } | |
| if !reflect.DeepEqual(expect, got) { | |
| fmt.Printf("expect:\n%s\nbut got:\n%s\n", expect.toString(), got.toString()) | |
| } | |
| // fail case | |
| expect = *new(matrix) | |
| if !reflect.DeepEqual(expect, got) { | |
| fmt.Printf("expect:\n%s\nbut got:\n%s\n", expect.toString(), got.toString()) | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| expect: | |
| but got: | |
| 12 14 10 | |
| 11 17 10 | |
| 8 6 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment