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

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 */
function flip_sum($x) {
    return 12 - $x;
}

/* 2. Product trick: 5 * 7 = 35 */
function flip_product($x) {
    return 35 / $x;
}

/* 3. XOR trick: 5 ^ 7 = 2
      x ^ 2 flips 5 ↔ 7 */
function flip_xor($x) {
    return $x ^ 2;
}

/* 4. Modulo-based trick using divisibility:
      $x % 7 == 0 → x is 7
      $x % 5 == 0 → x is 5
   Boolean → int via (int) cast */
function flip_mod($x) {
    return 5 * (int)($x % 7 == 0)
         + 7 * (int)($x % 5 == 0);
}

/* 5. Absolute-value trick: |x - 12| flips 5 ↔ 7 */
function flip_abs($x) {
    return 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 */
function flip_array($x) {
    $table = [7, 5];
    $index = ($x - 5) / 2;
    return $table[$index];
}

echo "flip_sum(5) = " . flip_sum(5) . PHP_EOL;
echo "flip_sum(7) = " . flip_sum(7) . PHP_EOL . PHP_EOL;

echo "flip_product(5) = " . flip_product(5) . PHP_EOL;
echo "flip_product(7) = " . flip_product(7) . PHP_EOL . PHP_EOL;

echo "flip_xor(5) = " . flip_xor(5) . PHP_EOL;
echo "flip_xor(7) = " . flip_xor(7) . PHP_EOL . PHP_EOL;

echo "flip_mod(5) = " . flip_mod(5) . PHP_EOL;
echo "flip_mod(7) = " . flip_mod(7) . PHP_EOL . PHP_EOL;

echo "flip_abs(5) = " . flip_abs(5) . PHP_EOL;
echo "flip_abs(7) = " . flip_abs(7) . PHP_EOL . PHP_EOL;

echo "flip_array(5) = " . flip_array(5) . PHP_EOL;
echo "flip_array(7) = " . flip_array(7) . PHP_EOL;



/*
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 Mar 31 by avibootz

Related questions

...