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, crearás un sistema sencillo de gestión de inventario para una tienda pequeña. Usarás punteros para actualizar las cantidades del inventario, calcular valores y realizar un seguimiento de los cambios.

Completa las tres funciones siguientes:

  1. updateQuantity(quantity *int, change int) (int, bool)
    Modifica el valor de quantity sumándole change (negativo para las ventas, positivo para las reposiciones).
    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 se ha quedado sin existencias (*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 en itemName usando los punteros.
    Devuelve totalValue.
  3. displayInventory(apples, oranges, bananas *int, applePrice, orangePrice, bananaPrice float64)
    Imprime el nombre de cada artículo, su cantidad (obtenida mediante la desreferenciación de su puntero) y su valor calculado usando fmt.Printf.
    Formato: Apples: 10 (Value: $5.00): usa %.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: Usa *quantity para leer o escribir el valor al que apunta un puntero. Por ejemplo, *quantity += change modifica directamente la variable original.

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 (quantity = 0)
func updateQuantity(quantity *int, change int) (int, bool) {
    // TODO: Actualiza el puntero quantity y devuelve el nuevo valor y el estado de agotado
    return 0, false
}

// calculateValue calcula el valor total de un artículo basándose en quantity y price
// It also updates the mostValuableItem if this item is more valuable
func calculateValue(itemName string, quantity int, price float64, mostValuableItem *string, highestValue *float64) float64 {
    // TODO: Calculate the total value, update mostValuableItem if needed, and return the total value
    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
    
    // Track the most valuable item
    var mostValuableItem string
    var highestValue float64
    
    // Display initial inventory
    fmt.Println("Initial Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // Calculate initial values and find most valuable item
    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) // Vende 4 manzanas
    _, orangesOutOfStock := updateQuantity(&oranges, -8) // Vende 8 naranjas
    _, bananasOutOfStock := updateQuantity(&bananas, -10) // Intenta vender 10 plátanos (más de los que tenemos)
    
    // Check if any items are out of stock
    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!")
    }
    
    // Display updated inventory
    fmt.Println("\nUpdated Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // Reset most valuable tracking for recalculation
    mostValuableItem = ""
    highestValue = 0
    
    // Recalcula los 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)
    
    // Reabastece los artículos
    fmt.Println("Restocking...")
    updateQuantity(&apples, 5)  // Añade 5 manzanas
    updateQuantity(&oranges, 10) // Añade 10 naranjas
    updateQuantity(&bananas, 12) // Añade 12 plátanos
    
    // Display final inventory
    fmt.Println("\nFinal Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // Reset most valuable tracking for final calculation
    mostValuableItem = ""
    highestValue = 0
    
    // Cálculo final del valor
    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

Practica por tu cuenta: Compilador de Go online