Challenge 13 - Smallest Difference between Ints
👋 Welcome Gophers! In this challenge, you are tasked with finding the smallest difference between two slices of int
values.
Example: Let’s say I have 2 int arrays; [1, 2] and [4, 5]. The function should return the smallest difference which would be the difference between
2
and4
.
View Solution
package main
import "fmt"
import "sort"
func CalcSmallestDifference(arr1, arr2 []int) int {
sort.Ints(arr1)
sort.Ints(arr2)
greater1 := arr1[len(arr1)-1]
smaller2 := arr2[0]
if (greater1 >= smaller2) {
return 0
}
return smaller2 - greater1
}
func main() {
fmt.Println("Smallest Difference Challenge")
arr1 := []int{9, 8, 7, 6}
arr2 := []int{7, 3, 2, 5}
smallestDiff := CalcSmallestDifference(arr1, arr2)
fmt.Println(smallestDiff)
}
Further Reading:
If you enjoyed this challenge, you may also enjoy some of the other challenges on this site: