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

1 Answer

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

object FlipNumbers {

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

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

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

  // 4. Modulo-based trick using divisibility:
  //    x % 7 == 0 → x is 7
  //    x % 5 == 0 → x is 5
  //    Boolean → Int via .compare(false) or .toInt in Scala 3
  def flipMod(x: Int): Int =
    5 * (if (x % 7 == 0) 1 else 0) +
    7 * (if (x % 5 == 0) 1 else 0)

  // 5. Absolute-value trick: |x - 12| flips 5 ↔ 7
  def flipAbs(x: Int): Int =
    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
  def flipArray(x: Int): Int = {
    val table = Array(7, 5)
    val index = (x - 5) / 2
    table(index)
  }

  def main(args: Array[String]): Unit = {
    println(s"flip_sum(5) = ${flipSum(5)}")
    println(s"flip_sum(7) = ${flipSum(7)}")
    println()

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

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

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

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

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

...