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

1 Answer

0 votes
import Foundation

/*
    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 {
    12 - x
}

// 2. Product trick: 5 * 7 = 35
func flipProduct(_ x: Int) -> Int {
    35 / x
}

// 3. XOR trick: 5 ^ 7 = 2
//    x ^ 2 flips 5 ↔ 7
func flipXor(_ x: Int) -> Int {
    x ^ 2
}

// 4. Modulo-based trick using divisibility:
//    x % 7 == 0 → x is 7
//    x % 5 == 0 → x is 5
//    Bool → Int via ternary
func flipMod(_ x: Int) -> Int {
    5 * (x % 7 == 0 ? 1 : 0)
  + 7 * (x % 5 == 0 ? 1 : 0)
}

// 5. Absolute-value trick: |x - 12| flips 5 ↔ 7
func flipAbs(_ x: Int) -> Int {
    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
func flipArray(_ x: Int) -> Int {
    let table = [7, 5]
    let index = (x - 5) / 2
    return table[index]
}

// --- Test functions ---

print("flip_sum(5) =", flipSum(5))
print("flip_sum(7) =", flipSum(7))
print()

print("flip_product(5) =", flipProduct(5))
print("flip_product(7) =", flipProduct(7))
print()

print("flip_xor(5) =", flipXor(5))
print("flip_xor(7) =", flipXor(7))
print()

print("flip_mod(5) =", flipMod(5))
print("flip_mod(7) =", flipMod(7))
print()

print("flip_abs(5) =", flipAbs(5))
print("flip_abs(7) =", flipAbs(7))
print()

print("flip_array(5) =", flipArray(5))
print("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

...