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

1 Answer

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

// 1. Arithmetic sum trick: 5 + 7 = 12
fun flipSum(x: Int): Int =
    12 - x

// 2. Product trick: 5 * 7 = 35
fun flipProduct(x: Int): Int =
    35 / x

// 3. XOR trick: 5 xor 7 = 2
//    x xor 2 flips 5 ↔ 7
fun flipXor(x: Int): Int =
    x xor 2

// 4. Modulo-based trick using divisibility:
//    x % 7 == 0 → x is 7
//    x % 5 == 0 → x is 5
//    Boolean → Int via .compareTo(false) or .let { if (it) 1 else 0 }
fun flipMod(x: Int): Int =
    5 * (x % 7 == 0).compareTo(false) +
    7 * (x % 5 == 0).compareTo(false)

// 5. Absolute-value trick: |x - 12| flips 5 ↔ 7
fun flipAbs(x: Int): Int =
    kotlin.math.abs(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
fun flipArray(x: Int): Int {
    val table = arrayOf(7, 5)
    val index = (x - 5) / 2
    return table[index]
}

fun main() {
    println("flip_sum(5) = ${flipSum(5)}")
    println("flip_sum(7) = ${flipSum(7)}")
    println()

    println("flip_product(5) = ${flipProduct(5)}")
    println("flip_product(7) = ${flipProduct(7)}")
    println()

    println("flip_xor(5) = ${flipXor(5)}")
    println("flip_xor(7) = ${flipXor(7)}")
    println()

    println("flip_mod(5) = ${flipMod(5)}")
    println("flip_mod(7) = ${flipMod(7)}")
    println()

    println("flip_abs(5) = ${flipAbs(5)}")
    println("flip_abs(7) = ${flipAbs(7)}")
    println()

    println("flip_array(5) = ${flipArray(5)}")
    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

...