Sha256: 758377afd35df2c6fcd1d8d80f076b38351207adcf296fea44e7274c4b67926d

Contents?: true

Size: 1.28 KB

Versions: 274

Compression:

Stored size: 1.28 KB

Contents

package matrix

import (
	"errors"
	"strconv"
	"strings"
)

// Maintenance note:  This file exists as both matrix/example.go and
// saddle-points/matrix_example.go.  When changing one file, copy to the other.

const testVersion = 1

type Matrix [][]int

func New(s string) (*Matrix, error) {
	var err error
	lines := strings.Split(s, "\n")
	m := make(Matrix, len(lines))
	for i, l := range lines {
		ws := strings.Fields(l)
		if i > 0 && len(ws) != len(m[0]) {
			return nil, errors.New("rows have unequal length")
		}
		row := make([]int, len(ws))
		for i, w := range ws {
			if row[i], err = strconv.Atoi(w); err != nil {
				return nil, errors.New("invalid int in element data")
			}
		}
		m[i] = row
	}
	return &m, nil
}

func (m *Matrix) Set(row, col, val int) (ok bool) {
	mm := *m
	if row < 0 || row >= len(mm) || col < 0 {
		return false
	}
	if cols := len(mm[0]); col >= cols {
		return false
	}
	mm[row][col] = val
	return true
}

func (m *Matrix) Rows() [][]int {
	r := make([][]int, len(*m))
	for i, mr := range *m {
		r[i] = append([]int{}, mr...)
	}
	return r
}

func (m *Matrix) Cols() [][]int {
	mm := *m
	if len(mm) == 0 {
		return nil
	}
	c := make([][]int, len(mm[0]))
	for i := range c {
		col := make([]int, len(mm))
		for j := range col {
			col[j] = mm[j][i]
		}
		c[i] = col
	}
	return c
}

Version data entries

274 entries across 274 versions & 1 rubygems

Version Path
trackler-2.1.0.39 tracks/go/exercises/matrix/example.go
trackler-2.1.0.38 tracks/go/exercises/matrix/example.go
trackler-2.1.0.37 tracks/go/exercises/matrix/example.go
trackler-2.1.0.36 tracks/go/exercises/matrix/example.go
trackler-2.1.0.34 tracks/go/exercises/matrix/example.go
trackler-2.1.0.33 tracks/go/exercises/matrix/example.go
trackler-2.1.0.32 tracks/go/exercises/matrix/example.go
trackler-2.1.0.31 tracks/go/exercises/matrix/example.go
trackler-2.1.0.30 tracks/go/exercises/matrix/example.go
trackler-2.1.0.29 tracks/go/exercises/matrix/example.go
trackler-2.1.0.28 tracks/go/exercises/matrix/example.go
trackler-2.1.0.27 tracks/go/exercises/matrix/example.go
trackler-2.1.0.26 tracks/go/exercises/matrix/example.go
trackler-2.1.0.25 tracks/go/exercises/matrix/example.go
trackler-2.1.0.24 tracks/go/exercises/matrix/example.go
trackler-2.1.0.23 tracks/go/exercises/matrix/example.go
trackler-2.1.0.22 tracks/go/exercises/matrix/example.go
trackler-2.1.0.21 tracks/go/exercises/matrix/example.go
trackler-2.1.0.20 tracks/go/exercises/matrix/example.go
trackler-2.1.0.19 tracks/go/exercises/matrix/example.go