Menu
Coddy logo textTech

Resumen: Entendiendo los punteros

Parte de la sección Fundamentos del Journey de GO de Coddy — lección 66 de 109.

challenge icon

Desafío

Intermedio

En este desafío, construirás un sistema simple de gestión de inventario para una pequeña tienda. Utilizarás punteros para actualizar las cantidades del inventario, calcular valores y realizar un seguimiento de los cambios.

Completa las tres funciones a continuación:

  1. updateQuantity(quantity *int, change int) (int, bool)
    Modifica el valor en quantity sumando change (negativo para ventas, positivo para reabastecimientos).
    Si el resultado fuera inferior a 0, establece *quantity en 0 en su lugar.
    Devuelve la nueva cantidad y un booleano que sea true si el artículo está ahora agotado (*quantity == 0).
  2. calculateValue(itemName string, quantity int, price float64, mostValuableItem *string, highestValue *float64) float64
    Calcula totalValue como float64(quantity) * price.
    Si totalValue es mayor que *highestValue, actualiza *highestValue y establece *mostValuableItem como itemName utilizando los punteros.
    Devuelve totalValue.
  3. displayInventory(apples, oranges, bananas *int, applePrice, orangePrice, bananaPrice float64)
    Imprime el nombre de cada artículo, la cantidad (desreferenciada de su puntero) y el valor calculado utilizando fmt.Printf.
    Formato: Apples: 10 (Value: $5.00) — utiliza %.2f para los precios.

La salida esperada para el inventario inicial es:

Initial Inventory:
Apples: 10 (Value: $5.00)
Oranges: 15 (Value: $10.50)
Bananas: 8 (Value: $2.40)
Total inventory value: $17.90
Most valuable item: Oranges

Consejo: Utiliza *quantity para leer o escribir el valor al que apunta un puntero. Por ejemplo, *quantity += change modifica la variable original directamente.

Pruébalo tú mismo

package main

import "fmt"

// updateQuantity actualiza la cantidad de un artículo y devuelve la nueva cantidad
// y si el artículo está agotado (cantidad = 0)
func updateQuantity(quantity *int, change int) (int, bool) {
    // TODO: Actualizar el puntero de cantidad y devolver el nuevo valor y el estado de agotado
    return 0, false
}

// calculateValue calcula el valor total de un artículo basado en la cantidad y el precio
// También actualiza mostValuableItem si este artículo es más valioso
func calculateValue(itemName string, quantity int, price float64, mostValuableItem *string, highestValue *float64) float64 {
    // TODO: Calcular el valor total, actualizar mostValuableItem si es necesario, y devolver el valor total
    return 0.0
}

// displayInventory imprime los detalles del inventario
// Toma punteros para permitir que la función muestre datos en tiempo real
func displayInventory(apples, oranges, bananas *int, applePrice, orangePrice, bananaPrice float64) {
    fmt.Printf("Apples: %d (Value: $%.2f)\n", *apples, float64(*apples) * applePrice)
    fmt.Printf("Oranges: %d (Value: $%.2f)\n", *oranges, float64(*oranges) * orangePrice)
    fmt.Printf("Bananas: %d (Value: $%.2f)\n", *bananas, float64(*bananas) * bananaPrice)
}

func main() {
    // Inicializar inventario
    apples := 10
    oranges := 15
    bananas := 8
    
    // Precios
    applePrice := 0.5  // $0.50 cada uno
    orangePrice := 0.7 // $0.70 cada uno
    bananaPrice := 0.3 // $0.30 cada uno
    
    // Rastrear el artículo más valioso
    var mostValuableItem string
    var highestValue float64
    
    // Mostrar inventario inicial
    fmt.Println("Initial Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // Calcular valores iniciales y encontrar el artículo más valioso
    appleValue := calculateValue("Apples", apples, applePrice, &mostValuableItem, &highestValue)
    orangeValue := calculateValue("Oranges", oranges, orangePrice, &mostValuableItem, &highestValue)
    bananaValue := calculateValue("Bananas", bananas, bananaPrice, &mostValuableItem, &highestValue)
    
    fmt.Printf("Total inventory value: $%.2f\n", appleValue+orangeValue+bananaValue)
    fmt.Printf("Most valuable item: %s\n\n", mostValuableItem)
    
    // Simular algunas ventas
    fmt.Println("Processing sales...")
    _, applesOutOfStock := updateQuantity(&apples, -4) // Vender 4 manzanas
    _, orangesOutOfStock := updateQuantity(&oranges, -8) // Vender 8 naranjas
    _, bananasOutOfStock := updateQuantity(&bananas, -10) // Intentar vender 10 bananas (más de las que tenemos)
    
    // Comprobar si algún artículo está agotado
    if applesOutOfStock {
        fmt.Println("Apples are out of stock!")
    }
    if orangesOutOfStock {
        fmt.Println("Oranges are out of stock!")
    }
    if bananasOutOfStock {
        fmt.Println("Bananas are out of stock!")
    }
    
    // Mostrar inventario actualizado
    fmt.Println("\nUpdated Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // Reiniciar el rastreo del más valioso para el recálculo
    mostValuableItem = ""
    highestValue = 0
    
    // Recalcular valores
    appleValue = calculateValue("Apples", apples, applePrice, &mostValuableItem, &highestValue)
    orangeValue = calculateValue("Oranges", oranges, orangePrice, &mostValuableItem, &highestValue)
    bananaValue = calculateValue("Bananas", bananas, bananaPrice, &mostValuableItem, &highestValue)
    
    fmt.Printf("Total inventory value: $%.2f\n", appleValue+orangeValue+bananaValue)
    fmt.Printf("Most valuable item: %s\n\n", mostValuableItem)
    
    // Reponer artículos
    fmt.Println("Restocking...")
    updateQuantity(&apples, 5)  // Añadir 5 manzanas
    updateQuantity(&oranges, 10) // Añadir 10 naranjas
    updateQuantity(&bananas, 12) // Añadir 12 bananas
    
    // Mostrar inventario final
    fmt.Println("\nFinal Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // Reiniciar el rastreo del más valioso para el cálculo final
    mostValuableItem = ""
    highestValue = 0
    
    // Cálculo del valor final
    appleValue = calculateValue("Apples", apples, applePrice, &mostValuableItem, &highestValue)
    orangeValue = calculateValue("Oranges", oranges, orangePrice, &mostValuableItem, &highestValue)
    bananaValue = calculateValue("Bananas", bananas, bananaPrice, &mostValuableItem, &highestValue)
    
    fmt.Printf("Total inventory value: $%.2f\n", appleValue+orangeValue+bananaValue)
    fmt.Printf("Most valuable item: %s\n", mostValuableItem)
}

Todas las lecciones de Fundamentos