fun fibonacci(n: Int): Int {
var a = 1
var b = 1
for (i in 2 until n) {
val temp = a + b
a = b
b = temp
}
return b
}
fun square(n: Int): Int = n * n
fun cube(n: Int): Int = n * n * n
fun collatzDepth(n: Int): Int {
var current = n
var depth = 1
while (current != 1) {
depth++
current = if (current % 2 == 0) {
current / 2
} else {
3 * current + 1
}
}
return depth
}
data class MenuItem(val text: String, val function: (Int) -> Int)
object Menu {
val items = mutableListOf<MenuItem>()
init {
items.add(MenuItem("Square", ::square))
items.add(MenuItem("Cube", ::cube))
items.add(MenuItem("Fibonacci", ::fibonacci))
items.add(MenuItem("Collatz Depth", ::collatzDepth))
}
}
fun main() {
do {
// Print the menu of functions as a numbered list
Menu.items.forEachIndexed { index, menuItem ->
println("${index + 1}. ${menuItem.text}")
}
println("Enter the number of the function to execute, or 0 to exit:")
val inputFunction = readLine()?.toIntOrNull() ?: 0
if (inputFunction == 0) break
if (inputFunction !in 1..Menu.items.size) {
println("Invalid selection. Please try again.")
continue
}
println("Enter an integer argument for the function:")
val inputArgument = readLine()?.toIntOrNull()
if (inputArgument == null) {
println("Invalid input. Please enter an integer.")
continue
}
val selectedMenuItem = Menu.items[inputFunction - 1]
val result = selectedMenuItem.function(inputArgument)
println("Result: $result")
} while (true)
println("Exiting...")
}
Comments
0 B
|👍
/👎
0 B
|👍
/👎