Menu
Coddy logo textTech

Generare un report

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

challenge icon

Sfida

Facile

Completa il tuo sistema di gestione dell’inventario implementando una funzione di reportistica completa che fornisca informazioni dettagliate sull’inventario attuale. Questa sfida si basa su tutte le funzionalità precedenti e aggiunge la possibilità di generare report formattati con statistiche, classificazioni e analisi.

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 la configurazione del report nel formato "report_type,threshold_value", dove report_type può essere "full", "low_stock" oppure "high_value" e threshold_value è un numero (ad es., "low_stock,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 suddividendolo in corrispondenza delle virgole per ottenere le singole voci dei prodotti esistenti
  3. Per ogni voce di prodotto esistente, suddividerla 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 dei prodotti esistenti
  6. Creare una funzione chiamata generateReport che accetti come parametri la mappa dell’inventario, il tipo di report e il valore soglia
  7. Analizzare il secondo input suddividendolo in corrispondenza delle virgole per ottenere il tipo di report e il valore soglia
  8. Convertire la stringa del valore soglia in float64
  9. Visualizzare l’intestazione del report in base al tipo di report:
    • Per "full": "=== FULL INVENTORY REPORT ==="
    • Per "low_stock": "=== LOW STOCK REPORT ==="
    • Per "high_value": "=== HIGH VALUE REPORT ==="
  10. Visualizzare le statistiche generali dell’inventario:
    • "Total Products: [total_number_of_products]"
    • "Total Items in Stock: [sum_of_all_quantities]"
    • "Total Inventory Value: $[sum_of_price_times_quantity_for_all_products]"
    • "Average Product Price: $[total_inventory_value_divided_by_total_items]"
  11. Filtrare e visualizzare i prodotti in base al tipo di report:
    • Per "full": mostrare tutti i prodotti
    • Per "low_stock": mostrare solo i prodotti con una quantità minore o uguale al valore soglia
    • Per "high_value": mostrare solo i prodotti con un valore totale (prezzo × quantità) maggiore o uguale al valore soglia
  12. Visualizzare la sezione dei prodotti filtrati:
    • Per "full": "All Products:"
    • Per "low_stock": "Products with stock ≤ [threshold_value]:"
    • Per "high_value": "Products with value ≥ $[threshold_value]:"
  13. Per ogni prodotto filtrato (in ordine alfabetico per nome del prodotto):
    • "- [product_name]: $[price] × [quantity] = $[total_value]"
  14. Visualizzare le statistiche dei risultati filtrati:
    • "Filtered Results:"
    • "Products shown: [number_of_products_in_filtered_results]"
    • "Items in filtered products: [sum_of_quantities_for_filtered_products]"
    • "Value of filtered products: $[sum_of_values_for_filtered_products]"
  15. Trovare e visualizzare i prodotti più e meno costosi:
    • "Price Analysis:"
    • "Most expensive: [product_name] at $[price]"
    • "Least expensive: [product_name] at $[price]"
  16. Trovare e visualizzare i prodotti con le scorte più alte e più basse:
    • "Stock Analysis:"
    • "Highest stock: [product_name] with [quantity] units"
    • "Lowest stock: [product_name] with [quantity] units"
  17. Visualizzare la valutazione dello stato dell’inventario:
    • Contare i prodotti con quantità ≤ 5: "Low stock items (≤5): [count]"
    • Contare i prodotti con quantità > 20: "High stock items (>20): [count]"
    • Contare i prodotti con valore ≥ $500: "High value items (≥$500): [count]"
  18. Visualizzare il completamento del report:
    • "Report generated successfully"
    • "Threshold applied: [threshold_value]"

Usa il pacchetto strings per suddividere le stringhe di input, il pacchetto strconv per convertire le stringhe in numeri, il pacchetto fmt per l’output formattato e il pacchetto sort per ordinare alfabeticamente i nomi dei prodotti. Formatta tutti i prezzi e i valori con 2 cifre decimali. Quando individui i prodotti più/meno costosi o con le scorte più alte/più basse, in caso di parità scegli il nome del prodotto che viene prima in ordine alfabetico. Questa sfida mostra come creare sistemi di reportistica completi che forniscono informazioni aziendali preziose attraverso l’analisi dei dati e una presentazione formattata.

Provalo tu

package main

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

type Product struct {
	Price    float64
	Quantity int
}

func updateStock(inventory map[string]Product, productName string, change int) error {
	product, exists := inventory[productName]
	if !exists {
		return errors.New("product not found: " + productName)
	}
	
	newQuantity := product.Quantity + change
	if newQuantity < 0 {
		return fmt.Errorf("insufficient stock: cannot reduce %s by %d, only %d available", productName, -change, product.Quantity)
	}
	
	product.Quantity = newQuantity
	inventory[productName] = product
	return nil
}

func main() {
	var inventoryData string
	var updateRequests string
	fmt.Scanln(&inventoryData)
	fmt.Scanln(&updateRequests)
	
	// Parse existing inventory
	inventory := make(map[string]Product)
	inventoryEntries := strings.Split(inventoryData, ",")
	
	for _, entry := range inventoryEntries {
		parts := strings.Split(entry, ":")
		name := parts[0]
		price, _ := strconv.ParseFloat(parts[1], 64)
		quantity, _ := strconv.Atoi(parts[2])
		
		inventory[name] = Product{
			Price:    price,
			Quantity: quantity,
		}
	}
	
	// Parse update requests
	updateEntries := strings.Split(updateRequests, ",")
	
	fmt.Println("Processing Stock Updates:")
	
	totalUpdates := len(updateEntries)
	successfulUpdates := 0
	failedUpdates := 0
	var failedProducts []string
	
	for _, update := range updateEntries {
		parts := strings.Split(update, ":")
		productName := parts[0]
		change, _ := strconv.Atoi(parts[1])
		
		err := updateStock(inventory, productName, change)
		if err != nil {
			fmt.Printf("%s: Update failed - %s\n", productName, err.Error())
			failedUpdates++
			failedProducts = append(failedProducts, productName)
		} else {
			newQuantity := inventory[productName].Quantity
			if change > 0 {
				fmt.Printf("%s: Added %d units - New stock: %d\n", productName, change, newQuantity)
			} else if change < 0 {
				fmt.Printf("%s: Removed %d units - New stock: %d\n", productName, -change, newQuantity)
			} else {
				fmt.Printf("%s: No change - Current stock: %d\n", productName, newQuantity)
			}
			successfulUpdates++
		}
	}
	
	// Update summary
	fmt.Println("Update Summary:")
	fmt.Printf("Updates processed: %d\n", totalUpdates)
	fmt.Printf("Updates successful: %d\n", successfulUpdates)
	fmt.Printf("Updates failed: %d\n", failedUpdates)
	
	// Display updated inventory in alphabetical order
	fmt.Println("Updated 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)
	}
	
	// Calculate final statistics
	totalProducts := len(inventory)
	totalItems := 0
	totalValue := 0.0
	
	for _, product := range inventory {
		totalItems += product.Quantity
		totalValue += product.Price * float64(product.Quantity)
	}
	
	fmt.Println("Final 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)
	
	// List failed updates
	if len(failedProducts) > 0 {
		fmt.Printf("Failed updates: %s\n", strings.Join(failedProducts, ","))
	} else {
		fmt.Println("All stock updates were processed successfully")
	}
}

Tutte le lezioni di Logica e flusso

Esercitati da solo: Compilatore Go online