Skip to content

Instantly share code, notes, and snippets.

@barthr
Last active May 1, 2017 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barthr/bb9e7d279483a2be4246c0375feaaf2d to your computer and use it in GitHub Desktop.
Save barthr/bb9e7d279483a2be4246c0375feaaf2d to your computer and use it in GitHub Desktop.
Vector class for golang
package statistic
import "math"
type Vector []float64
func (v Vector) Equal(other Vector) bool {
if other == nil || v == nil {
return false
}
if v.Size() != other.Size() {
return false
}
for index, value := range other {
if value != v[index] {
return false
}
}
return true
}
func (v Vector) Distance(other Vector) float64 {
sum := .0
if v.Size() != other.Size() {
return sum
}
for i := 0; i < v.Size(); i++ {
subtraction := v[i] - other[i]
sqrtResult := math.Pow(subtraction, 2)
sum += sqrtResult
}
return math.Sqrt(sum)
}
func (v *Vector) Add(val float64) {
(*v) = append((*v), val)
}
func (v Vector) Size() int {
return len(v)
}
package statistic
import (
"testing"
)
func TestVector_Equal(t *testing.T) {
type args struct {
other Vector
}
tests := []struct {
name string
v Vector
args args
want bool
}{
{
name: "Testing comparison to empty vector",
v: Vector{},
args: args{
nil,
},
want: false,
},
{
name: "Testing empty vector",
v: nil,
args: args{
nil,
},
want: false,
},
{
name: "Testing non empty vector comparison where the lenghts aren't the same",
v: Vector{},
args: args{
Vector{.0},
},
want: false,
},
{
name: "Testing non empty vector with same length but different values",
v: Vector{.1},
args: args{
Vector{.0},
},
want: false,
},
{
name: "Testing non empty vector with same length and same values",
v: Vector{.1, .1, .2},
args: args{
Vector{.1, .1, .2},
},
want: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.v.Equal(tt.args.other); got != tt.want {
t.Errorf("Vector.Equal() = %v, want %v", got, tt.want)
}
})
}
}
func TestVector_Distance(t *testing.T) {
type args struct {
other Vector
}
tests := []struct {
name string
v Vector
args args
want float64
}{
{
name: "Testing empty vector",
v: nil,
args: args{
nil,
},
want: .0,
},
{
name: "Testing vector without the same size",
v: Vector{.0},
args: args{
Vector{},
},
want: .0,
},
{
name: "Testing vector With the same size",
v: Vector{.1, .2, 20.70},
args: args{
Vector{.1, 20.70, 20.70},
},
want: 20.5,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.v.Distance(tt.args.other); got != tt.want {
t.Errorf("Vector.Distance() = %v, want %v", got, tt.want)
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment