Practice Time: Lambdas

 

Practice Time: Lambdas

  1. Create a lambda and assign it to rollDice, which returns a dice roll (number between 1 and 12).
  2. Extend the lambda to take an argument indicating the number of sides of the dice used for the roll.
  3. If you haven't done so, fix the lambda to return 0 if the number of sides passed in is 0.
  4. Create a new variable, rollDice2, for this same lambda using the function type notation.
  5. Create a function gamePlay() that takes a roll of the dice as an argument and prints it out.
  6. Pass your rollDice2 function as an argument to gamePlay() to generate a dice roll every time gamePlay() is called.

import java.util.Random

// File: Main.kt
// Programmer: Engineer Nolverto Urias Obeso
// Creation Date: 06/15/2023
// Email: nolvertou@gmail.com
// Description: Learning how to use the lambda

fun main(args: Array<String>) {

//Create a lambda and assign it to rollDice, which returns a dice roll (number between 1 and 12).
val rollDice1 = {Random().nextInt(12) + 1}
println("Testing rollDice1:")
// Testing the results of rollDice
for (item in 1 .. 30){
print(rollDice1().toString() + if(item!=30){", "}else "\n")
}

// Extend the lambda to take an argument indicating the number of sides of the dice used for the roll.
val rollDice2: (Int) -> Int = {sides-> Random().nextInt(sides) + 1}
println("Testing rollDice2:")
for (item in 1 .. 30){
print(rollDice2(6).toString() + if(item!=30){", "}else "\n")
}

// If you haven't done so, fix the lambda to return 0 if the number of sides passed in is 0.
val rollDice3: (Int) -> Int = {sides -> if(sides > 0) Random().nextInt(sides) + 1 else 0}
println("Testing rollDice3:")
for (item in 1 .. 30){
print(rollDice3(0).toString() + if(item!=30){", "}else "\n")
}

val rollDice4 = {sides: Int -> if(sides > 0) Random().nextInt(sides) + 1 else 0}
println("Testing rollDice4:")
for (item in 1 .. 30){
print(rollDice4(18).toString() + if(item!=30){", "}else "\n")
}


// Create a function gamePlay() that takes a roll of the dice as an argument and prints it out.
// Pass your rollDice2 function as an argument to gamePlay() to generate a dice roll every time gamePlay() is called.
val gamePlay = {rollDice: Int -> println(rollDice) }
println("Testing gamePlay lambda:")
gamePlay(rollDice4(6))

fun gamePlay(rollDice: Int){
println(rollDice)
}
println("Testing gamePlay function:")
gamePlay(rollDice4(60))


}

Comments

Popular posts from this blog