Guest User

Untitled

a guest
Oct 21st, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "sort"
  6. )
  7.  
  8. func hasAverage(angles []int) (bool, int) {
  9. var differ bool // false
  10. if len(angles) == 0 {
  11. // We have no angles, return false and -1
  12. return false, -1
  13. }
  14. if len(angles) == 1 {
  15. // Only one angle, easy, return that one
  16. return true, angles[0]
  17. }
  18. // Check if the angles are different
  19. for _, a := range angles {
  20. if a != angles[0] {
  21. differ = true
  22. break
  23. }
  24. }
  25. // Only similar angles? Return the first one
  26. if !differ {
  27. return true, angles[0]
  28. }
  29. return false, 0
  30. }
  31.  
  32. func average(angles []int) int {
  33. lastIndex := len(angles) - 1
  34. sort.SortInts(angles)
  35. for {
  36. if indeed, angle := hasAverage(angles); indeed {
  37. return angle
  38. }
  39. // There are more than one angle
  40. for i := lastIndex; i > 1; i-- {
  41. // Move all angles around, towards each other
  42. if angles[i] > angles[i - 1] {
  43. angles[i]--
  44. } else if angles[i] < angles[i - 1] {
  45. angles[i]++
  46. }
  47. }
  48. if angles[0] > angles[lastIndex] {
  49. angles[0]--
  50. } else if angles[0] < angles[lastIndex] {
  51. angles[0]++
  52. }
  53. //fmt.Println(angles)
  54. }
  55. return -1
  56. }
  57.  
  58. func main() {
  59. var angles1 []int = []int{1, 359, 2, 358}
  60. var angles2 []int = []int{-180, 180}
  61. fmt.Println(average(angles1))
  62. fmt.Println(average(angles2))
  63. }
Add Comment
Please, Sign In to add comment