Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a built in min function for a slice of int arguments or a variable number of int arguments in golang?

Tags:

go

Precursor: I'm just starting to get my feet wet with golang.

This may prove to a be a silly question as it's quite easy to perform these calculations but I'm going to ask it anyway as I didn't find an answer when Googling.

Is there a built in function that returns the minimum of a slice of int arguments:

func MinIntSlice(v []int) (m int) {
    if len(v) > 0 {
        m = v[0]
    }
    for i := 1; i < len(v); i++ {
        if v[i] < m {
            m = v[i]
        }
    }
    return
}

OR the minimum of a variable number of int arguments:

func MinIntVarible(v1 int, vn ...int) (m int) {
    m = v1
    for i := 0; i < len(vn); i++ {
        if vn[i] < m {
            m = vn[i]
        }
    }
    return
}

If not, is the best "convention" simply to create a package that contains helpers like this?

like image 833
Jesse Avatar asked Dec 14 '15 04:12

Jesse


3 Answers

There is no built-in for this.

If you need this functionality only in one package you can write an un-exported function (e.g. minIntSlice).

If you need this functionality in multiple packages you can create a package and put similar functions there. You should consider making this package internal (https://golang.org/s/go14internal).

A few suggestions how to improve your code:

  1. MinIntSlice will return 0 for an empty slice. However 0 is a valid min element as well. I think calling panic on an empty slice is a better option.

  2. Use range loop:

    for i, e := range v {
        if i==0 || e < m {
            m = e
        }
    }
    

by not giving the index of value it will give you the minimum value 0, which may not be present in given values, so you also have to apply condition on index.

like image 108
kostya Avatar answered Nov 19 '22 11:11

kostya


As @kostya correctly stated there is no built-in min or max function in Golang.

However, I would suggest a slightly different solution:

func MinMax(array []int) (int, int) {
    var max int = array[0]
    var min int = array[0]
    for _, value := range array {
        if max < value {
            max = value
        }
        if min > value {
            min = value
        }
    }
    return min, max
}

By that the problem of an empty slice is solved: a runtime error shows up (index out of range) and the max value is for free. :-)

like image 42
Michael Dorner Avatar answered Nov 19 '22 11:11

Michael Dorner


    min := s[0]
    for i :=1; i < len(s); i++ {
        if min > s[i] {
            min = s[i]
        }
    }

min > s[i]? min = s[i] : min

like image 4
funnyDev Avatar answered Nov 19 '22 09:11

funnyDev