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

1 Answer

0 votes
program FlipNumbers;

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

uses
    Math;  { for Abs() }

{ 1. Arithmetic sum trick: 5 + 7 = 12 }
function FlipSum(x: Integer): Integer;
begin
    FlipSum := 12 - x;
end;

{ 2. Product trick: 5 * 7 = 35 }
function FlipProduct(x: Integer): Integer;
begin
    FlipProduct := 35 div x;
end;

{ 3. XOR trick: 5 xor 7 = 2
      x xor 2 flips 5 ↔ 7 }
function FlipXor(x: Integer): Integer;
begin
    FlipXor := x xor 2;
end;

{ 4. Modulo-based trick using divisibility:
      x mod 7 = 0 → x is 7
      x mod 5 = 0 → x is 5
  Boolean expressions evaluate to 0 or 1 in arithmetic. }
function FlipMod(x: Integer): Integer;
begin
    FlipMod := 5 * Ord(x mod 7 = 0) + 7 * Ord(x mod 5 = 0);
end;

{ 5. Absolute-value trick: |x - 12| flips 5 ↔ 7 }
function FlipAbs(x: Integer): Integer;
begin
    FlipAbs := Abs(x - 12);
end;

{ 6. Array lookup using boolean indexing }
function FlipArray(x: Integer): Integer;
const
    Table: array[0..1] of Integer = (7, 5);
begin
    { x = 5 → (x = 5) = TRUE → Ord(TRUE) = 1 → Table[1] = 5
      x = 7 → (x = 5) = FALSE → Ord(FALSE) = 0 → Table[0] = 7 }
    FlipArray := Table[Ord(x = 5)];
end;

begin
    Writeln('flip_sum(5) = ', FlipSum(5));
    Writeln('flip_sum(7) = ', FlipSum(7));
    Writeln;

    Writeln('flip_product(5) = ', FlipProduct(5));
    Writeln('flip_product(7) = ', FlipProduct(7));
    Writeln;

    Writeln('flip_xor(5) = ', FlipXor(5));
    Writeln('flip_xor(7) = ', FlipXor(7));
    Writeln;

    Writeln('flip_mod(5) = ', FlipMod(5));
    Writeln('flip_mod(7) = ', FlipMod(7));
    Writeln;

    Writeln('flip_abs(5) = ', FlipAbs(5));
    Writeln('flip_abs(7) = ', FlipAbs(7));
    Writeln;

    Writeln('flip_array(5) = ', FlipArray(5));
    Writeln('flip_array(7) = ', FlipArray(7));
end.



{
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) = 5
flip_array(7) = 7

}

 



answered Mar 31 by avibootz

Related questions

...