Sunday, April 14, 2024
HomeSoftware EngineeringThe way to Discover the Smallest Integer within the Array in Golang

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

## The problem#

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

For instance:

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

You possibly can assume, for the aim of this problem, that the equipped array won’t be empty.

Possibility 1:

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

Possibility 2:

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

Possibility 3:

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

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

``````package deal solution_test
import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"math/rand"
"kind"
"time"
)
func _solution(numbers []int) int {
kind.Ints(numbers)
return numbers[0]
}
var _ = Describe("Take a look at Instance", func() {
It("ought to work for pattern checks", 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 checks", 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