How to check whether a number is positive/zero/negative without using conditional statements in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

func main() {
    n := 89

    // create text labels for each possible case
    result := []string{
        "negative",  // index 0
        "zero",      // index 1
        "positive",  // index 2
    }

    // compute an index without using any conditional statements
    // (n > 0) becomes 1 if true, 0 if false
    // (n < 0) becomes 1 if true, 0 if false
    // index = 1 + (n > 0) - (n < 0)
    index := 1 + btoi(n > 0) - btoi(n < 0)

    // print the classification
    fmt.Println(result[index])

    /*
       Checks:

       n = -3
       (n > 0) = 0
       (n < 0) = 1
       index = 1 + 0 - 1 = 0
       result = negative

       n = 0
       (n > 0) = 0
       (n < 0) = 0
       index = 1 + 0 - 0 = 1
       result = zero

       n = 89
       (n > 0) = 1
       (n < 0) = 0
       index = 1 + 1 - 0 = 2
       result = positive
    */
}

// helper: convert bool → int (true=1, false=0)
func btoi(b bool) int {
    if b {
        return 1
    }
    return 0
}



/*
run:

positive

*/

 



answered Jun 27 by avibootz

Related questions

...