How to Reverse Sort Integers in Go


The challenge

The two oldest ages function/method needs to be completed. It should take an array of numbers as its argument and return the two highest numbers within the array. The returned value should be an array in the format [second oldest age, oldest age].

The order of the numbers passed in could be any order. The array will always include at least 2 items. If there are two or more oldest age, then return both of them in array format.

For example:

TwoOldestAges([]int{1, 5, 87, 45, 8, 8}) // should return [2]int{45, 87}

The solution in Go

Option 1:

package solution
import "sort"
func TwoOldestAges(ages []int) [2]int {
  sort.Sort(sort.Reverse(sort.IntSlice(ages)))
  return [2]int{ages[1],ages[0]}
}

Option 2:

package solution
func TwoOldestAges(ages []int) [2]int {
  a, b := 0, 0
  for _, v := range ages {
    if v > b {
      a, b = b, v
    } else if v > a {
      a = v
    }
  }
  return [2]int{a, b}
}

Option 3:

package solution
import "sort"
func TwoOldestAges(ages []int) [2]int {
  sort.Ints(ages)
  return [2]int{ages[len(ages)-2],ages[len(ages)-1]}
}

Test cases to validate our solution

package solution_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
var _ = Describe("TwoOldestAges", func() {
  It("should return 18 and 83 for input []int{6,5,83,5,3,18}", func() {
    Expect(TwoOldestAges([]int{6,5,83,5,3,18})).To(Equal([2]int{18,83}))
  })
  It("should return 45 and 87 for input []int{1,5,87,45,8,8}", func() {
    Expect(TwoOldestAges([]int{1,5,87,45,8,8})).To(Equal([2]int{45,87}))
  })
})