PageRenderTime 153ms CodeModel.GetById 61ms app.highlight 12ms RepoModel.GetById 78ms app.codeStats 0ms

/gt/matrix.go

https://code.google.com/p/go-gt/
Go | 130 lines | 112 code | 17 blank | 1 comment | 30 complexity | d3d8d56e0486c547718dba35e68c9d1d MD5 | raw file
  1package gt
  2
  3import (
  4	"bufio"
  5	"fmt"
  6	"math/rand"
  7	"strconv"
  8)
  9
 10type Vector []int64
 11
 12type Matrix struct {
 13	N int64
 14	A []int64
 15}
 16
 17func NewMatrix(n int64) (m *Matrix) {
 18	m = new(Matrix)
 19	m.N = n
 20	m.A = make([]int64, n*n)
 21	return m
 22}
 23
 24func (m Matrix) Get(i int64, j int64) int64 {
 25	return m.A[i*m.N+j]
 26}
 27
 28func (m Matrix) Set(i int64, j int64, v int64) {
 29	m.A[i*m.N+j] = v
 30}
 31
 32func (p Vector) Swap(i int64, j int64) {
 33	x := p[i]
 34	p[i] = p[j]
 35	p[j] = x
 36}
 37
 38func (v Vector) Len() int64 {
 39	return int64(len(v))
 40}
 41
 42func (v Vector) Copy(w Vector) {
 43	for i := 0; i < len(v); i++ {
 44		v[i] = w[i]
 45	}
 46}
 47
 48func (v Vector) Print() {
 49	for i := 0; i < len(v); i++ {
 50		fmt.Printf("%d ", v[i])
 51	}
 52	fmt.Print("\n")
 53}
 54
 55func (m *Matrix) Print() {
 56	var i, j int64
 57	for i = 0; i < m.N; i++ {
 58		for j = 0; j < m.N; j++ {
 59			fmt.Printf("%d ", m.Get(i, j))
 60		}
 61		fmt.Print("\n")
 62	}
 63}
 64
 65// generate a random permutation p
 66func Perm(p Vector) {
 67	n := int64(len(p))
 68	var i int64
 69	for i = 0; i < n; i++ {
 70		p[i] = int64(i)
 71	}
 72	for i = 0; i < n; i++ {
 73		p.Swap(i, i+rand.Int63n(n-i))
 74	}
 75}
 76
 77func skip(rd *bufio.Reader) {
 78	var b byte = ' '
 79	var err error
 80	for b == ' ' || b == '\t' || b == '\n' {
 81		b, err = rd.ReadByte()
 82		if err != nil {
 83			return
 84		}
 85	}
 86	rd.UnreadByte()
 87}
 88
 89func wskip(s string) string {
 90	for i := 0; i < len(s); i++ {
 91		if s[i] != ' ' && s[i] != '\t' {
 92			return s[i:]
 93		}
 94	}
 95	return ""
 96}
 97
 98func end(s string) (i int64) {
 99	for i = 0; i < int64(len(s)); i++ {
100		if s[i] == ' ' || s[i] == '\t' || s[i] == '\n' {
101			return i
102		}
103	}
104	return 0
105}
106
107func readUint(s string) (int64, int64) {
108	i := end(s)
109	x, _ := strconv.ParseInt(s[:i], 10, 64)
110	return int64(x), i
111}
112
113func readMatrix(rd *bufio.Reader, n int64) *Matrix {
114	M := NewMatrix(n)
115	var i, j int64
116	for i = 0; i < n; i++ {
117		skip(rd)
118		line, _ := rd.ReadString('\n')
119		for j = 0; j < n; j++ {
120			line = wskip(line)
121			x, p := readUint(line)
122			M.Set(j, i, x)
123			if p == 0 {
124				panic("bad int")
125			}
126			line = line[p:]
127		}
128	}
129	return M
130}