Wednesday, February 21, 2024
HomeSoftware EngineeringFind out how to Reverse Type Integers in Go

Find out how to Reverse Type Integers in Go

The problem#

The 2 oldest ages perform/technique must be accomplished. It ought to take an array of numbers as its argument and return the two highest numbers throughout the array. The returned worth ought 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 embody at the least 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:

``````package deal 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:

``````package deal 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:

``````package deal 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 instances to validate our resolution#

``````package deal 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() {
Anticipate(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() {
Anticipate(TwoOldestAges([]int{1,5,87,45,8,8})).To(Equal([2]int{45,87}))
})
})
``````
RELATED ARTICLES