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.2.1.56 tracks/go/exercises/matrix/example.go
trackler-2.2.1.55 tracks/go/exercises/matrix/example.go
trackler-2.2.1.54 tracks/go/exercises/matrix/example.go
trackler-2.2.1.53 tracks/go/exercises/matrix/example.go
trackler-2.2.1.52 tracks/go/exercises/matrix/example.go
trackler-2.2.1.51 tracks/go/exercises/matrix/example.go
trackler-2.2.1.50 tracks/go/exercises/matrix/example.go
trackler-2.2.1.49 tracks/go/exercises/matrix/example.go
trackler-2.2.1.48 tracks/go/exercises/matrix/example.go
trackler-2.2.1.47 tracks/go/exercises/matrix/example.go
trackler-2.2.1.46 tracks/go/exercises/matrix/example.go
trackler-2.2.1.45 tracks/go/exercises/matrix/example.go
trackler-2.2.1.44 tracks/go/exercises/matrix/example.go
trackler-2.2.1.43 tracks/go/exercises/matrix/example.go
trackler-2.2.1.42 tracks/go/exercises/matrix/example.go
trackler-2.2.1.41 tracks/go/exercises/matrix/example.go
trackler-2.2.1.40 tracks/go/exercises/matrix/example.go
trackler-2.2.1.39 tracks/go/exercises/matrix/example.go
trackler-2.2.1.38 tracks/go/exercises/matrix/example.go
trackler-2.2.1.37 tracks/go/exercises/matrix/example.go