Convertir while a foreach
Antes, escribiste un bucle while con estilo imperativo para encontrar e imprimir los puntos necesarios para pasarse en cinco manos (una por cada jugador) en una ronda de Twenty-One:
// Define counter variable
var i = 0
// Create list with five hands of Twenty-One
var hands = List(16, 21, 8, 25, 4)
// Loop through hands
while(i < hands.length) {
// Find and print number of points to bust
println(pointsToBust(hands(i)))
// Increment the counter variable
i += 1
}
En este ejercicio, vas a convertir ese código a un estilo más funcional, preferido en Scala, usando el método foreach. La función bust ya está definida para ti. En el código de ejemplo se proporciona una versión modificada de pointsToBust (con println).
Este ejercicio forma parte del curso
Introducción a Scala
Instrucciones del ejercicio
- Llama al método
foreachsobre el array de arrayshands, recorriendo cada ronda para obtener los puntos necesarios para pasarse usando la funciónpointsToBust.
Ejercicio interactivo práctico
Prueba este ejercicio y completa el código de muestra.
// Find the number of points that will cause a bust
def pointsToBust(hand: Int) = {
// If the hand is a bust, 0 points remain
if (bust(hand))
println(0)
// Otherwise, calculate the difference between 21 and the current hand
else
println(21 - hand)
}
// Create list with five hands of Twenty-One
var hands = List(16, 21, 8, 25, 4)
// Loop through hands, finding each hand's number of points to bust
___