Initial Commit

This commit is contained in:
2016-08-13 18:20:14 -05:00
commit 50f4a86fd8
408 changed files with 15301 additions and 0 deletions

27
go/triangle/README.md Normal file
View File

@@ -0,0 +1,27 @@
# Triangle
Write a program that can tell you if a triangle is equilateral, isosceles, or scalene.
The program should raise an error if the triangle cannot exist.
Tests are provided, delete one `skip` at a time.
## Hint
The sum of the lengths of any two sides of a triangle always exceeds the
length of the third side, a principle known as the _triangle
inequality_.
To run the tests simply run the command `go test` in the exercise directory.
If the test suite contains benchmarks, you can run these with the `-bench`
flag:
go test -bench .
For more detailed info about the Go track see the [help
page](http://help.exercism.io/getting-started-with-go.html).
## Source
The Ruby Koans triangle project, parts 1 & 2 [view source](http://rubykoans.com)

30
go/triangle/triangle.go Normal file
View File

@@ -0,0 +1,30 @@
package triangle
// KindFromSides returns what type of triangle has the sides
// of length a, b, and c
func KindFromSides(a, b, c float64) Kind {
if a+b > c && b+c > a && a+c > b {
if a == b && b == c {
return Equ
}
if a == b || b == c || a == c {
return Iso
}
return Sca
}
return NaT
}
// Kind describes the different types of triangles
type Kind int
const (
// Equ - equilateral
Equ = iota
// Iso - isosceles
Iso
// Sca - scalene
Sca
// NaT - not a triangle
NaT
)

View File

@@ -0,0 +1,66 @@
package triangle
import (
"math"
"testing"
)
type testCase struct {
want Kind
a, b, c float64
}
// basic test cases
var testData = []testCase{
{Equ, 2, 2, 2}, // same length
{Equ, 10, 10, 10}, // a little bigger
{Iso, 3, 4, 4}, // last two sides equal
{Iso, 4, 3, 4}, // first and last sides equal
{Iso, 4, 4, 3}, // first two sides equal
{Iso, 10, 10, 2}, // again
{Sca, 3, 4, 5}, // no sides equal
{Sca, 10, 11, 12}, // again
{Sca, 5, 4, 2}, // descending order
{Sca, .4, .6, .3}, // small sides
{NaT, 0, 0, 0}, // zero length
{NaT, 3, 4, -5}, // negative length
{NaT, 1, 1, 3}, // fails triangle inequality
{NaT, 2, 4, 2}, // another
{NaT, 7, 3, 2}, // another
}
// generate cases with NaN and Infs, append to basic cases
func init() {
nan := math.NaN()
pinf := math.Inf(1)
ninf := math.Inf(-1)
nf := make([]testCase, 4*4*4)
i := 0
for _, a := range []float64{3, nan, pinf, ninf} {
for _, b := range []float64{4, nan, pinf, ninf} {
for _, c := range []float64{5, nan, pinf, ninf} {
nf[i] = testCase{NaT, a, b, c}
i++
}
}
}
testData = append(testData, nf[1:]...)
}
func TestKind(t *testing.T) {
for _, test := range testData {
got := KindFromSides(test.a, test.b, test.c)
if got != test.want {
t.Fatalf("Triangle with sides, %g, %g, %g = %v, want %v",
test.a, test.b, test.c, got, test.want)
}
}
}
func BenchmarkKind(b *testing.B) {
for i := 0; i < b.N; i++ {
for _, test := range testData {
KindFromSides(test.a, test.b, test.c)
}
}
}