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

1 Answer

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

// 1. Arithmetic sum trick: 5 + 7 = 12
fn flip_sum(x: i32) -> i32 {
    12 - x
}

// 2. Product trick: 5 * 7 = 35
fn flip_product(x: i32) -> i32 {
    35 / x
}

// 3. XOR trick: 5 ^ 7 = 2
//    x ^ 2 flips 5 ↔ 7
fn flip_xor(x: i32) -> i32 {
    x ^ 2
}

// 4. Modulo-based trick using divisibility:
//    x % 7 == 0 → x is 7
//    x % 5 == 0 → x is 5
//    Boolean → integer via as i32
fn flip_mod(x: i32) -> i32 {
    5 * ((x % 7 == 0) as i32)
        + 7 * ((x % 5 == 0) as i32)
}

// 5. Absolute-value trick: |x - 12| flips 5 ↔ 7
fn flip_abs(x: i32) -> i32 {
    (x - 12).abs()
}

// 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
fn flip_array(x: i32) -> i32 {
    let table = [7, 5];
    let index = (x - 5) / 2;
    table[index as usize]
}

fn main() {
    println!("flip_sum(5) = {}", flip_sum(5));
    println!("flip_sum(7) = {}", flip_sum(7));
    println!();

    println!("flip_product(5) = {}", flip_product(5));
    println!("flip_product(7) = {}", flip_product(7));
    println!();

    println!("flip_xor(5) = {}", flip_xor(5));
    println!("flip_xor(7) = {}", flip_xor(7));
    println!();

    println!("flip_mod(5) = {}", flip_mod(5));
    println!("flip_mod(7) = {}", flip_mod(7));
    println!();

    println!("flip_abs(5) = {}", flip_abs(5));
    println!("flip_abs(7) = {}", flip_abs(7));
    println!();

    println!("flip_array(5) = {}", flip_array(5));
    println!("flip_array(7) = {}", flip_array(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

...