Thursday, November 23, 2023
HomeSoftware EngineeringThe best way to Discover the Smallest Integer within the Array in...

The best way to Discover the Smallest Integer within the Array in Golang

The problem#

Given an array of integers your resolution ought to discover the smallest integer.

For instance:

• Given `[34, 15, 88, 2]` your resolution will return `2`
• Given `[34, -345, -1, 100]` your resolution will return `-345`

You’ll be able to assume, for the aim of this problem, that the equipped array won’t be empty.

Possibility 1:

``````package deal resolution
func SmallestIntegerFinder(numbers []int) int {
curr := numbers[0]
for _, v := vary numbers {
if v<curr {
curr = v
}
}
return curr
}
``````

Possibility 2:

``````package deal resolution
import "type"
func SmallestIntegerFinder(numbers []int) int {
type.Ints(numbers)
return numbers[0]
}
``````

Possibility 3:

``````package deal resolution
func SmallestIntegerFinder(numbers []int) int {
return quickSort(numbers)[0]
}
func quickSort( enter []int) []int{
if len(enter)==0 {
return []int{}
}
index:=len(enter)/2
temp:=enter[index]
var decrease []int
var better []int
for i:= vary enter{
if i==index {
proceed
}
if enter[i] <= temp {
decrease = append(decrease, enter[i])
} else {
better = append(better, enter[i])
}
}
outcome:=append(quickSort(decrease), temp)
return append(outcome, quickSort(better)...)
}
``````

Take a look at circumstances to validate our resolution#

``````package deal solution_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"math/rand"
"type"
"time"
)
func _solution(numbers []int) int {
type.Ints(numbers)
return numbers[0]
}
var _ = Describe("Take a look at Instance", func() {
It("ought to work for pattern exams", func() {
Count on(Count on(SmallestIntegerFinder([]int{34, 15, 88, 2})).To(Equal(2)))
Count on(Count on(SmallestIntegerFinder([]int{34, -345, -1, 100})).To(Equal(-345)))
})
rand.Seed(time.Now().UTC().UnixNano())
min, max := -100, 100
It("ought to work for random exams", func() {
for i := 0; i < 500; i++ {
arrLen := 10 + rand.Intn(100)
var arrInts []int
for j := 0; j < arrLen; j++ {
arrInts = append(arrInts, rand.Intn(max - min + 1) + min)
}
ts := SmallestIntegerFinder(arrInts)
r := _solution(arrInts)
Count on(ts).To(Equal(r))
}
})
})
``````
RELATED ARTICLES