How to write 6 different functions that accept 5 or 7 and return the other number, without using if,switch in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "math"
)

/*
   Six different functions that accept 5 or 7
   and return the other number, without using if/switch.
*/

// 1. Arithmetic sum trick: 5 + 7 = 12
func flipSum(x int) int {
    return 12 - x
}

// 2. Product trick: 5 * 7 = 35
func flipProduct(x int) int {
    return 35 / x
}

// 3. XOR trick: 5 ^ 7 = 2
//    x ^ 2 flips 5 ↔ 7
func flipXor(x int) int {
    return x ^ 2
}

// 4. Modulo-based trick using divisibility:
//    x % 7 == 0 → x is 7
//    x % 5 == 0 → x is 5
//    Boolean → int via ternary-like conversion
func flipMod(x int) int {
    toInt := func(b bool) int {
        if b {
            return 1
        }
        return 0
    }
    return 5*toInt(x%7 == 0) + 7*toInt(x%5 == 0)
}

// 5. Absolute-value trick: |x - 12| flips 5 ↔ 7
func flipAbs(x int) int {
    return int(math.Abs(float64(x - 12)))
}

// 6. Array lookup using arithmetic index:
//    For x = 5 → (5 - 5) / 2 = 0 → table[0] = 7
//    For x = 7 → (7 - 5) / 2 = 1 → table[1] = 5
func flipArray(x int) int {
    table := []int{7, 5}
    index := (x - 5) / 2
    return table[index]
}

func main() {
    fmt.Println("flip_sum(5) =", flipSum(5))
    fmt.Println("flip_sum(7) =", flipSum(7))
    fmt.Println()

    fmt.Println("flip_product(5) =", flipProduct(5))
    fmt.Println("flip_product(7) =", flipProduct(7))
    fmt.Println()

    fmt.Println("flip_xor(5) =", flipXor(5))
    fmt.Println("flip_xor(7) =", flipXor(7))
    fmt.Println()

    fmt.Println("flip_mod(5) =", flipMod(5))
    fmt.Println("flip_mod(7) =", flipMod(7))
    fmt.Println()

    fmt.Println("flip_abs(5) =", flipAbs(5))
    fmt.Println("flip_abs(7) =", flipAbs(7))
    fmt.Println()

    fmt.Println("flip_array(5) =", flipArray(5))
    fmt.Println("flip_array(7) =", flipArray(7))
}

/*
OUTPUT:

flip_sum(5) = 7
flip_sum(7) = 5

flip_product(5) = 7
flip_product(7) = 5

flip_xor(5) = 7
flip_xor(7) = 5

flip_mod(5) = 7
flip_mod(7) = 5

flip_abs(5) = 7
flip_abs(7) = 5

flip_array(5) = 7
flip_array(7) = 5

*/

 



answered Apr 1 by avibootz

Related questions

...