Saturday, December 9, 2023
HomeSoftware EngineeringThe right way to Reverse Type Integers in Go

# The right way to Reverse Type Integers in Go

## The problem#

The 2 oldest ages operate/methodology must be accomplished. It ought to take an array of numbers as its argument and return the two highest numbers inside the array. The returned worth needs to be an array within the format [second oldest age, oldest age].

The order of the numbers handed in may very well be any order. The array will all the time embrace not less than 2 gadgets. If there are two or extra oldest age, then return each of them in array format.

For instance:

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

Choice 1:

bundle resolution
import "type"
func TwoOldestAges(ages []int) [2]int {
type.Type(type.Reverse(type.IntSlice(ages)))
return [2]int{ages[1],ages[0]}
}

Choice 2:

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

Choice 3:

bundle resolution
import "type"
func TwoOldestAges(ages []int) [2]int {
type.Ints(ages)
return [2]int{ages[len(ages)-2],ages[len(ages)-1]}
}

## Take a look at circumstances to validate our resolution#

bundle solution_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("TwoOldestAges", func() {
It("ought to return 18 and 83 for enter []int{6,5,83,5,3,18}", func() {
Count on(TwoOldestAges([]int{6,5,83,5,3,18})).To(Equal([2]int{18,83}))
})
It("ought to return 45 and 87 for enter []int{1,5,87,45,8,8}", func() {
Count on(TwoOldestAges([]int{1,5,87,45,8,8})).To(Equal([2]int{45,87}))
})
})
RELATED ARTICLES