Sunday, February 19, 2023
HomeSoftware EngineeringEasy methods to Discover the Smallest Integer within the Array in Golang

# Easy methods 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 possibly can assume, for the aim of this problem, that the equipped array won’t be empty.

## The answer in Golang#

Choice 1:

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

Choice 2:

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

Choice 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 higher []int
for i:= vary enter{
if i==index {
proceed
}
if enter[i] <= temp {
decrease = append(decrease, enter[i])
} else {
higher = append(higher, enter[i])
}
}
consequence:=append(quickSort(decrease), temp)
return append(consequence, quickSort(higher)...)
}
``````

## Check 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("Check Instance", func() {
It("ought to work for pattern assessments", func() {
Anticipate(Anticipate(SmallestIntegerFinder([]int{34, 15, 88, 2})).To(Equal(2)))
Anticipate(Anticipate(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 assessments", 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)
Anticipate(ts).To(Equal(r))
}
})
})
``````

RELATED ARTICLES