How to Find the Smallest Integer in the Array in Golang

The challenge

Given an array of integers your solution should find the smallest integer.

For example:

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

You can assume, for the purpose of this challenge, that the supplied array will not be empty.

The solution in Golang

Option 1:

package solution func SmallestIntegerFinder(numbers []int) int { curr := numbers[0] for _, v := range numbers { if v<curr { curr = v } } return curr }
Code language: Go (go)

Option 2:

package solution import "sort" func SmallestIntegerFinder(numbers []int) int { sort.Ints(numbers) return numbers[0] }
Code language: Go (go)

Option 3:

package solution func SmallestIntegerFinder(numbers []int) int { return quickSort(numbers)[0] } func quickSort( input []int) []int{ if len(input)==0 { return []int{} } index:=len(input)/2 temp:=input[index] var lower []int var greater []int for i:= range input{ if i==index { continue } if input[i] <= temp { lower = append(lower, input[i]) } else { greater = append(greater, input[i]) } } result:=append(quickSort(lower), temp) return append(result, quickSort(greater)...) }
Code language: Go (go)

Test cases to validate our solution

package solution_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "math/rand" "sort" "time" ) func _solution(numbers []int) int { sort.Ints(numbers) return numbers[0] } var _ = Describe("Test Example", func() { It("should work for sample tests", func() { Expect(Expect(SmallestIntegerFinder([]int{34, 15, 88, 2})).To(Equal(2))) Expect(Expect(SmallestIntegerFinder([]int{34, -345, -1, 100})).To(Equal(-345))) }) rand.Seed(time.Now().UTC().UnixNano()) min, max := -100, 100 It("should work for random tests", 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) Expect(ts).To(Equal(r)) } }) })
Code language: Go (go)

Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments