find the range of all elements in an array in go

To find the range of all elements in an array in Go, we need to iterate over the array and keep track of the minimum and maximum values. Here's an example implementation:

main.go
func findRange(arr []int) (int, int) {
    min := arr[0]
    max := arr[0]
    for _, num := range arr {
        if num < min {
            min = num
        }
        if num > max {
            max = num
        }
    }
    return min, max
}
243 chars
14 lines

This function takes an array of integers as input and returns the minimum and maximum values as output. We initialize the minimum and maximum values to the first element of the array, and then iterate over the rest of the array, updating the minimum and maximum values as needed.

To use this function, we can simply call it with our array as input:

main.go
arr := []int{1, 5, 3, 9, 2, 6}
min, max := findRange(arr)
fmt.Printf("Range: %d-%d\n", min, max)
97 chars
4 lines

This will output:

main.go
Range: 1-9
11 chars
2 lines

related categories

gistlibby LogSnag