Home > database >  checking array if contains two condition
checking array if contains two condition

Time:08-17

Suppose I have the following

if arr contains negative and positive number, should return 0. if arr only have positive number, return the smallest number (except 0). if arr only have negative number, return the biggest number (except 0).

func sesi(arr []int) int {
minmax := arr[0]
for _, v := range arr {
    if v >= 0 && v <= 0 {
        minmax=0
        return minmax
    } else if v > 0 {
        if v < minmax {
            minmax = v
            return minmax
        }
    } else if v < 0 {
        if v < minmax {
            minmax = v
            return minmax
        }
    }
}
return minmax }

CodePudding user response:

So you're not accounting for the input being a slice of zeroes, I'm assuming in that case zero has to be returned. You also state that a slice of negative only values should return "the biggest number" I've assumed that this means the highest value (ie -123 < -1 => returns -1). By sorting the input slice, this is a trivial task to do:

func sesi(in []int) int {
    if len(in) == 0 {
        return 0 // check for empty input
    }
    sort.Ints(in) // sort the integers, in ascending order
    if in[0] < 0 {
        last := in[len(in)-1] // highest value in the input
        if last > 0 {
            return 0 // lowest value is negative, highest is positive
        }
        return last // all negative (not checking for zeroes), return highest value
    }
    if in[0] > 0 || len(in) == 1 { // first element is positive > 0, or we only have 1 element (could be []int{0})
        return in[0]
    }
    for i := 1; i < len(in); i   {
        if in[i] > 0 {
            return in[i] // find smallest non-zero value in a positive slice
        }
    }
    return 0 // slice contains no values other than zeroes
}

Demo

If, by "biggest number" in an all-negative slice you actually meant to say the biggest absolute value (ie -123, -1 => return -123), you just need to change the bit where I'm assigning last := in[len(in)-1] to this:

if in[0] < 0 {
    if in[len(in)-1] > 0 {
        return 0
    }
    return in[0] // smallest value, largest absolute value
}

Nice and simple

  •  Tags:  
  • go
  • Related