Exercism: Go version of the 'Triangle' exercise.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.1 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. // Package triangle determines what kind of triangle three side lengths make.
  2. package triangle
  3. import "math"
  4. // An enumeration of triangle types
  5. const (
  6. NaT Kind = iota // Not a triangle
  7. Equ // Equlateral
  8. Iso // Isometric
  9. Sca // Scalene
  10. testVersion = 2
  11. )
  12. // A Kind is an integer representation of the kind of triangle.
  13. type Kind int
  14. // KindFromSides determines whether the three side lengths given
  15. // constitute a triangle and if so, what type of triangle it is.
  16. func KindFromSides(a, b, c float64) (k Kind) {
  17. // Return NaT when any side is zero, negative, infinite, or NaN.
  18. for _, f := range []float64{a, b, c} {
  19. if f <= 0 || f != f || math.IsInf(f, 0) {
  20. return NaT
  21. }
  22. }
  23. switch {
  24. // Return NaT if the sides fail triangle inequality tests.
  25. case a+b < c || b+c < a || a+c < b:
  26. k = NaT
  27. case a == b && b == c: // 3 equal length sides (Equ)
  28. k = Equ
  29. case a == b || b == c || a == c: // 2 equal length sides (Iso)
  30. k = Iso
  31. case a != b && b != c && a != c: // No equal length sides (Sca)
  32. k = Sca
  33. }
  34. return k
  35. }
  36. // Iteration 2 benkmark results:
  37. //
  38. // PASS
  39. // BenchmarkKind-12 2000000 651 ns/op
  40. //