Menu
Coddy logo textTech

Controllare le scorte

Fa parte della sezione Logica e flusso del percorso GO di Coddy. Lezione 46 di 68.

challenge icon

Sfida

Facile

Implementa una funzione di controllo delle scorte per il tuo sistema di gestione dell'inventario che recuperi in modo sicuro le quantità dei prodotti e gestisca i casi in cui i prodotti non esistono. Questa sfida si basa sulle fondamenta dell'inventario della lezione precedente e aggiunge la gestione degli errori per le richieste sulle scorte.

Riceverai due input:

  • Una stringa contenente i dati dell'inventario esistente nel formato "product1:price1:quantity1,product2:price2:quantity2,product3:price3:quantity3" (ad es., "Laptop:999.99:5,Mouse:25.50:15,Keyboard:75.00:8")
  • Una stringa contenente le richieste di controllo delle scorte nel formato "product1,product2,product3" (ad es., "Mouse,Tablet,Keyboard")

Il tuo compito è:

  1. Usare la stessa struct Product della lezione precedente con i campi Price (float64) e Quantity (int)
  2. Analizzare il primo input dividendolo in corrispondenza delle virgole per ottenere le singole voci dei prodotti
  3. Per ogni voce di prodotto, dividerla in corrispondenza dei due punti per ottenere il nome del prodotto, il prezzo e la quantità
  4. Convertire la stringa del prezzo in float64 e la stringa della quantità in int
  5. Creare e popolare la mappa inventory con i dati analizzati dei prodotti
  6. Creare una funzione chiamata checkStock che accetti come parametri la mappa dell'inventario e il nome di un prodotto e restituisca (int, error):
    • Se il prodotto esiste nell'inventario, restituire la sua quantità e nil
    • Se il prodotto non esiste, restituire 0 e un errore con il messaggio "product not found: [product_name]"
  7. Analizzare il secondo input dividendolo in corrispondenza delle virgole per ottenere l'elenco dei prodotti da controllare
  8. Visualizzare l'intestazione del controllo delle scorte: "Stock Check Results:"
  9. Per ogni prodotto nell'elenco da controllare, chiamare la funzione checkStock e visualizzare i risultati:
    • Se non ci sono errori: "[product_name]: [quantity] units in stock"
    • Se si verifica un errore: "[product_name]: Error - [error_message]"
  10. Contare e visualizzare le statistiche riepilogative:
    • "Check Summary:"
    • "Products checked: [total_number_of_products_checked]"
    • "Products found: [number_of_products_that_exist]"
    • "Products not found: [number_of_products_that_dont_exist]"
  11. Visualizzare le scorte totali dei prodotti trovati:
    • "Total stock for found products: [sum_of_quantities_for_existing_products] units"
  12. Elencare eventuali prodotti mancanti:
    • Se ci sono prodotti mancanti: "Missing products: [comma_separated_list_of_missing_products]"
    • Se non ci sono prodotti mancanti: "All requested products are available"

Usa il pacchetto strings per suddividere le stringhe di input, il pacchetto strconv per convertire le stringhe in numeri, il pacchetto errors per creare i messaggi di errore e il pacchetto fmt per l'output formattato. Questa sfida mostra come implementare il recupero sicuro dei dati con una corretta gestione degli errori, un modello fondamentale nei sistemi di gestione dell'inventario.

Provalo tu

package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
	"strings"
)

// Define the Product struct
type Product struct {
	Price    float64
	Quantity int
}

func main() {
	// Read input using bufio.Scanner to handle spaces properly
	scanner := bufio.NewScanner(os.Stdin)
	
	scanner.Scan()
	storeInfo := scanner.Text()
	
	scanner.Scan()
	productData := scanner.Text()
	
	// 1. Parse store information (split by comma)
	storeInfoParts := strings.Split(storeInfo, ",")
	storeName := ""
	location := ""
	if len(storeInfoParts) >= 2 {
		storeName = storeInfoParts[0]
		location = storeInfoParts[1]
	}
	
	// 2. Parse product data (split by comma, then by colon for each product)
	productEntries := strings.Split(productData, ",")
	
	// 3. Create inventory map
	inventory := make(map[string]Product)
	
	// 4. Convert strings to appropriate types and populate inventory
	for _, entry := range productEntries {
		parts := strings.Split(entry, ":")
		if len(parts) >= 3 {
			productName := parts[0]
			price, _ := strconv.ParseFloat(parts[1], 64)
			quantity, _ := strconv.Atoi(parts[2])
			
			inventory[productName] = Product{
				Price:    price,
				Quantity: quantity,
			}
		}
	}
	
	// 5. Display store information
	fmt.Printf("=== %s Inventory System ===\n", storeName)
	fmt.Printf("Location: %s\n", location)
	fmt.Printf("Inventory initialized with %d products\n", len(inventory))
	
	// 6. Display current inventory (sorted alphabetically)
	fmt.Println("Current Inventory:")
	var productNames []string
	for name := range inventory {
		productNames = append(productNames, name)
	}
	sort.Strings(productNames)
	
	for _, name := range productNames {
		product := inventory[name]
		fmt.Printf("- %s: $%.2f (Stock: %d)\n", name, product.Price, product.Quantity)
	}
	
	// 7. Calculate and display inventory statistics
	totalProducts := len(inventory)
	totalItems := 0
	totalValue := 0.0
	
	for _, product := range inventory {
		totalItems += product.Quantity
		totalValue += product.Price * float64(product.Quantity)
	}
	
	fmt.Println("Inventory Statistics:")
	fmt.Printf("Total Products: %d\n", totalProducts)
	fmt.Printf("Total Items in Stock: %d\n", totalItems)
	fmt.Printf("Total Inventory Value: $%.2f\n", totalValue)
	
	// 8. Display system status
	fmt.Println("System Status: Ready")
	fmt.Println("Inventory management system initialized successfully")
}

Tutte le lezioni di Logica e flusso

Esercitati da solo: Compilatore Go online