Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "sort"
- )
- func hasAverage(angles []int) (bool, int) {
- var differ bool // false
- if len(angles) == 0 {
- // We have no angles, return false and -1
- return false, -1
- }
- if len(angles) == 1 {
- // Only one angle, easy, return that one
- return true, angles[0]
- }
- // Check if the angles are different
- for _, a := range angles {
- if a != angles[0] {
- differ = true
- break
- }
- }
- // Only similar angles? Return the first one
- if !differ {
- return true, angles[0]
- }
- return false, 0
- }
- func average(angles []int) int {
- lastIndex := len(angles) - 1
- sort.SortInts(angles)
- for {
- if indeed, angle := hasAverage(angles); indeed {
- return angle
- }
- // There are more than one angle
- for i := lastIndex; i > 1; i-- {
- // Move all angles around, towards each other
- if angles[i] > angles[i - 1] {
- angles[i]--
- } else if angles[i] < angles[i - 1] {
- angles[i]++
- }
- }
- if angles[0] > angles[lastIndex] {
- angles[0]--
- } else if angles[0] < angles[lastIndex] {
- angles[0]++
- }
- //fmt.Println(angles)
- }
- return -1
- }
- func main() {
- var angles1 []int = []int{1, 359, 2, 358}
- var angles2 []int = []int{-180, 180}
- fmt.Println(average(angles1))
- fmt.Println(average(angles2))
- }
Add Comment
Please, Sign In to add comment