exercism/go/matrix/matrix.go

79 lines
1.5 KiB
Go
Raw Normal View History

2016-09-04 02:35:32 +00:00
package matrix
2016-09-05 03:25:19 +00:00
import (
"errors"
"strconv"
"strings"
)
2016-09-04 02:35:32 +00:00
2016-09-05 03:25:19 +00:00
// Matrix is a grid of ints
2016-09-04 02:35:32 +00:00
type Matrix struct {
vals [][]int
}
2016-09-05 03:25:19 +00:00
// New creates a new Matrix from a string of numbers
2016-09-04 02:35:32 +00:00
func New(in string) (*Matrix, error) {
ret := Matrix{}
rows := strings.Split(in, "\n")
2016-09-05 03:25:19 +00:00
for i := range rows {
flds := strings.Fields(rows[i])
var ints []int
for j := range flds {
if v, err := strconv.Atoi(flds[j]); err != nil {
return &ret, err
} else {
ints = append(ints, v)
}
}
ret.vals = append(ret.vals, ints)
}
numInRow := -1
for i := range ret.vals {
if numInRow != -1 {
if len(ret.vals[i]) != numInRow {
return &ret, errors.New("All rows must be equal length")
}
}
numInRow = len(ret.vals[i])
}
2016-09-04 02:35:32 +00:00
return &ret, nil
}
2016-09-05 03:25:19 +00:00
// Rows returns the values of the rows in the matrix
2016-09-04 02:35:32 +00:00
func (m *Matrix) Rows() [][]int {
2016-09-05 03:25:19 +00:00
var ret [][]int
for i := range m.vals {
var row []int
for j := range m.vals[i] {
row = append(row, m.vals[i][j])
}
ret = append(ret, row)
}
return ret
2016-09-04 02:35:32 +00:00
}
2016-09-05 03:25:19 +00:00
// Cols returns the values of the cols in the matrix
2016-09-04 02:35:32 +00:00
func (m *Matrix) Cols() [][]int {
2016-09-05 03:25:19 +00:00
var ret [][]int
for i := range m.vals[0] {
var row []int
for j := range m.vals {
row = append(row, m.vals[j][i])
}
ret = append(ret, row)
2016-09-04 02:35:32 +00:00
}
return ret
}
2016-09-05 03:25:19 +00:00
// Set sets the value at r,c to val
2016-09-04 02:35:32 +00:00
func (m *Matrix) Set(r, c int, val int) bool {
2016-09-05 03:25:19 +00:00
if r < 0 || c < 0 {
return false
}
if len(m.vals) <= r || len(m.vals[r]) <= c {
2016-09-04 02:35:32 +00:00
return false
}
m.vals[r][c] = val
return true
}