Menu
Coddy logo textTech

Mettere tutto insieme

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

challenge icon

Sfida

Facile

Completa il tuo sistema di gestione dell'inventario creando un programma principale completo che integri tutte le funzionalità realizzate nelle lezioni precedenti. Questa sfida finale riunisce l'inizializzazione dell'inventario, il controllo delle scorte, l'aggiunta di articoli, gli aggiornamenti delle scorte e la generazione di report in un'interfaccia completa a riga di comando con navigazione basata su menu.

Riceverai tre input:

  • Una stringa contenente i dati iniziali dell'inventario 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 una sequenza di operazioni di menu nel formato "operation1,operation2,operation3", in cui le operazioni possono essere "check", "add", "update", "report" o "exit" (ad es., "check,add,update,report,exit")
  • Una stringa contenente i parametri delle operazioni nel formato "param1|param2|param3", in cui ciascun parametro corrisponde all'operazione nella stessa posizione (ad es., "Mouse|Monitor:299.99:10|Laptop:5|full,10")

Il tuo compito è:

  1. Usare la stessa struct Product delle lezioni precedenti, con i campi Price (float64) e Quantity (int)
  2. Analizzare il primo input e inizializzare la mappa dell'inventario con i dati dei prodotti esistenti
  3. Visualizzare il messaggio di avvio del sistema:
    • "=== INVENTORY MANAGEMENT SYSTEM ==="
    • "System initialized with [number_of_products] products"
    • "Starting interactive session..."
  4. Analizzare il secondo input per ottenere la sequenza di operazioni da eseguire
  5. Analizzare il terzo input per ottenere i parametri di ciascuna operazione
  6. Per ogni operazione della sequenza, visualizzare l'intestazione dell'operazione ed eseguire l'azione corrispondente:
    • Per "check": visualizzare "--- STOCK CHECK ---" e controllare le scorte del prodotto specificato
    • Per "add": visualizzare "--- ADD ITEM ---" e aggiungere il prodotto specificato
    • Per "update": visualizzare "--- UPDATE STOCK ---" e aggiornare le scorte del prodotto specificato
    • Per "report": visualizzare "--- GENERATE REPORT ---" e generare il report specificato
    • Per "exit": visualizzare "--- SYSTEM EXIT ---" e mostrare le informazioni di uscita
  7. Implementare la funzione checkStock che restituisce la quantità e un errore, come nelle lezioni precedenti
  8. Implementare la funzione addNewItem che aggiunge prodotti e restituisce un errore, come nelle lezioni precedenti
  9. Implementare la funzione updateStock che aggiorna le quantità e restituisce un errore, come nelle lezioni precedenti
  10. Implementare la funzione generateReport che crea report, come nelle lezioni precedenti
  11. Per l'operazione "check":
    • Usare il parametro come nome del prodotto da controllare
    • Visualizzare: "Checking stock for: [product_name]"
    • Se trovato: "Stock level: [quantity] units"
    • Se non trovato: "Product not found in inventory"
  12. Per l'operazione "add":
    • Analizzare il parametro nel formato "product_name:price:quantity"
    • Visualizzare: "Adding new product: [product_name]"
    • Se l'operazione riesce: "Product added successfully"
    • Se non riesce: "Failed to add product: [error_message]"
  13. Per l'operazione "update":
    • Analizzare il parametro nel formato "product_name:change"
    • Visualizzare: "Updating stock for: [product_name]"
    • Se l'operazione riesce e la modifica è positiva: "Added [change] units. New stock: [new_quantity]"
    • Se l'operazione riesce e la modifica è negativa: "Removed [absolute_change] units. New stock: [new_quantity]"
    • Se non riesce: "Update failed: [error_message]"
  14. Per l'operazione "report":
    • Analizzare il parametro nel formato "report_type,threshold"
    • Visualizzare: "Generating [report_type] report with threshold [threshold]"
    • Generare e visualizzare il report completo come nelle lezioni precedenti
  15. Per l'operazione "exit":
    • Visualizzare le statistiche finali dell'inventario:
      • "Final inventory status:"
      • "Total products: [total_products]"
      • "Total items: [total_items]"
      • "Total value: $[total_value]"
    • Visualizzare: "Session completed successfully"
    • Visualizzare: "Thank you for using the Inventory Management System"
  16. Dopo ogni operazione (tranne exit), visualizzare: "Operation completed. Continuing to next operation..."

Usa il pacchetto strings per dividere le stringhe di input, il pacchetto strconv per convertire le stringhe in numeri, il pacchetto errors per la gestione degli errori, il pacchetto fmt per l'output formattato e il pacchetto sort per l'ordinamento alfabetico. Formatta tutti i prezzi e i valori con 2 cifre decimali. Questa sfida mostra come creare un sistema interattivo completo che integra più componenti funzionali in un'esperienza utente coerente, con una corretta gestione degli errori e dello stato.

Provalo tu

package main

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

type Product struct {
	Price    float64
	Quantity int
}

func generateReport(inventory map[string]Product, reportType string, threshold float64) {
	// Display report header
	switch reportType {
	case "full":
		fmt.Println("=== FULL INVENTORY REPORT ===")
	case "low_stock":
		fmt.Println("=== LOW STOCK REPORT ===")
	case "high_value":
		fmt.Println("=== HIGH VALUE REPORT ===")
	}

	// Calculate general statistics
	totalProducts := len(inventory)
	totalItems := 0
	totalValue := 0.0
	
	for _, product := range inventory {
		totalItems += product.Quantity
		totalValue += product.Price * float64(product.Quantity)
	}
	
	averagePrice := totalValue / float64(totalItems)

	// Display general 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)
	fmt.Printf("Average Product Price: $%.2f\n", averagePrice)

	// Filter products based on report type
	var filteredProducts []string
	for name, product := range inventory {
		switch reportType {
		case "full":
			filteredProducts = append(filteredProducts, name)
		case "low_stock":
			if product.Quantity <= int(threshold) {
				filteredProducts = append(filteredProducts, name)
			}
		case "high_value":
			productValue := product.Price * float64(product.Quantity)
			if productValue >= threshold {
				filteredProducts = append(filteredProducts, name)
			}
		}
	}

	// Sort filtered products alphabetically
	sort.Strings(filteredProducts)

	// Display filtered products section header
	switch reportType {
	case "full":
		fmt.Println("All Products:")
	case "low_stock":
		fmt.Printf("Products with stock ≤ %.0f:\n", threshold)
	case "high_value":
		fmt.Printf("Products with value ≥ $%.2f:\n", threshold)
	}

	// Display filtered products
	filteredItems := 0
	filteredValue := 0.0
	for _, name := range filteredProducts {
		product := inventory[name]
		productValue := product.Price * float64(product.Quantity)
		fmt.Printf("- %s: $%.2f × %d = $%.2f\n", name, product.Price, product.Quantity, productValue)
		filteredItems += product.Quantity
		filteredValue += productValue
	}

	// Display filtered statistics
	fmt.Println("Filtered Results:")
	fmt.Printf("Products shown: %d\n", len(filteredProducts))
	fmt.Printf("Items in filtered products: %d\n", filteredItems)
	fmt.Printf("Value of filtered products: $%.2f\n", filteredValue)

	// Find most and least expensive products
	var mostExpensiveName, leastExpensiveName string
	var mostExpensivePrice, leastExpensivePrice float64
	first := true
	
	var sortedNames []string
	for name := range inventory {
		sortedNames = append(sortedNames, name)
	}
	sort.Strings(sortedNames)
	
	for _, name := range sortedNames {
		product := inventory[name]
		if first {
			mostExpensiveName = name
			mostExpensivePrice = product.Price
			leastExpensiveName = name
			leastExpensivePrice = product.Price
			first = false
		} else {
			if product.Price > mostExpensivePrice {
				mostExpensiveName = name
				mostExpensivePrice = product.Price
			}
			if product.Price < leastExpensivePrice {
				leastExpensiveName = name
				leastExpensivePrice = product.Price
			}
		}
	}

	fmt.Println("Price Analysis:")
	fmt.Printf("Most expensive: %s at $%.2f\n", mostExpensiveName, mostExpensivePrice)
	fmt.Printf("Least expensive: %s at $%.2f\n", leastExpensiveName, leastExpensivePrice)

	// Find highest and lowest stock products
	var highestStockName, lowestStockName string
	var highestStock, lowestStock int
	first = true
	
	for _, name := range sortedNames {
		product := inventory[name]
		if first {
			highestStockName = name
			highestStock = product.Quantity
			lowestStockName = name
			lowestStock = product.Quantity
			first = false
		} else {
			if product.Quantity > highestStock {
				highestStockName = name
				highestStock = product.Quantity
			}
			if product.Quantity < lowestStock {
				lowestStockName = name
				lowestStock = product.Quantity
			}
		}
	}

	fmt.Println("Stock Analysis:")
	fmt.Printf("Highest stock: %s with %d units\n", highestStockName, highestStock)
	fmt.Printf("Lowest stock: %s with %d units\n", lowestStockName, lowestStock)

	// Inventory health assessment
	lowStockCount := 0
	highStockCount := 0
	highValueCount := 0
	
	for _, product := range inventory {
		if product.Quantity <= 5 {
			lowStockCount++
		}
		if product.Quantity > 20 {
			highStockCount++
		}
		productValue := product.Price * float64(product.Quantity)
		if productValue >= 500.0 {
			highValueCount++
		}
	}

	fmt.Printf("Low stock items (≤5): %d\n", lowStockCount)
	fmt.Printf("High stock items (>20): %d\n", highStockCount)
	fmt.Printf("High value items (≥$500): %d\n", highValueCount)

	// Report completion
	fmt.Println("Report generated successfully")
	fmt.Printf("Threshold applied: %.2f\n", threshold)
}

func main() {
	var inventoryData string
	var reportConfig string
	fmt.Scanln(&inventoryData)
	fmt.Scanln(&reportConfig)

	// Parse inventory data
	inventory := make(map[string]Product)
	if inventoryData != "" {
		products := strings.Split(inventoryData, ",")
		for _, productStr := range products {
			parts := strings.Split(productStr, ":")
			name := parts[0]
			price, _ := strconv.ParseFloat(parts[1], 64)
			quantity, _ := strconv.Atoi(parts[2])
			inventory[name] = Product{Price: price, Quantity: quantity}
		}
	}

	// Parse report configuration
	configParts := strings.Split(reportConfig, ",")
	reportType := configParts[0]
	threshold, _ := strconv.ParseFloat(configParts[1], 64)

	// Generate report
	generateReport(inventory, reportType, threshold)
}

Tutte le lezioni di Logica e flusso

Esercitati da solo: Compilatore Go online