Advertisement
markruff

function references

Mar 17th, 2024
1,323
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.85 KB | None | 0 0
  1. fun fibonacci(n: Int): Int {
  2.     var a = 1
  3.     var b = 1
  4.     for (i in 2 until n) {
  5.         val temp = a + b
  6.         a = b
  7.         b = temp
  8.     }
  9.     return b
  10. }
  11.  
  12. fun square(n: Int): Int = n * n
  13.  
  14. fun cube(n: Int): Int = n * n * n
  15.  
  16. fun collatzDepth(n: Int): Int {
  17.     var current = n
  18.     var depth = 1
  19.     while (current != 1) {
  20.         depth++
  21.         current = if (current % 2 == 0) {
  22.             current / 2
  23.         } else {
  24.             3 * current + 1
  25.         }
  26.     }
  27.     return depth
  28. }
  29.  
  30. data class MenuItem(val text: String, val function: (Int) -> Int)
  31.  
  32. object Menu {
  33.     val items = mutableListOf<MenuItem>()
  34.  
  35.     init {
  36.         items.add(MenuItem("Square", ::square))
  37.         items.add(MenuItem("Cube", ::cube))
  38.         items.add(MenuItem("Fibonacci", ::fibonacci))
  39.         items.add(MenuItem("Collatz Depth", ::collatzDepth))
  40.     }
  41. }
  42.  
  43. fun main() {
  44.     do {
  45.         // Print the menu of functions as a numbered list
  46.         Menu.items.forEachIndexed { index, menuItem ->
  47.             println("${index + 1}. ${menuItem.text}")
  48.         }
  49.  
  50.         println("Enter the number of the function to execute, or 0 to exit:")
  51.         val inputFunction = readLine()?.toIntOrNull() ?: 0
  52.  
  53.         if (inputFunction == 0) break
  54.  
  55.         if (inputFunction !in 1..Menu.items.size) {
  56.             println("Invalid selection. Please try again.")
  57.             continue
  58.         }
  59.  
  60.         println("Enter an integer argument for the function:")
  61.         val inputArgument = readLine()?.toIntOrNull()
  62.         if (inputArgument == null) {
  63.             println("Invalid input. Please enter an integer.")
  64.             continue
  65.         }
  66.  
  67.         val selectedMenuItem = Menu.items[inputFunction - 1]
  68.         val result = selectedMenuItem.function(inputArgument)
  69.         println("Result: $result")
  70.  
  71.     } while (true)
  72.  
  73.     println("Exiting...")
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement