Menu
Coddy logo textTech

הפקת דוח

חלק מהיחידה לוגיקה וזרימת התוכנית במסלול ה-GO של Coddy. שיעור 49 מתוך 68.

challenge icon

אתגר

קל

השלם את מערכת ניהול המלאי שלך על ידי מימוש פונקציית דיווח מקיפה שמספקת תובנות מפורטות על המלאי הנוכחי שלך. האתגר הזה מבוסס על כל הפונקציונליות הקודמת ומוסיף את היכולת להפיק דוחות מעוצבים הכוללים נתונים סטטיסטיים, סיווג וניתוח.

תקבל שתי קלטים:

  • מחרוזת המכילה נתוני מלאי קיימים בפורמט "product1:price1:quantity1,product2:price2:quantity2,product3:price3:quantity3" (למשל, "Laptop:999.99:5,Mouse:25.50:15,Keyboard:75.00:8")
  • מחרוזת המכילה תצורת דוח בפורמט "report_type,threshold_value", כאשר report_type יכול להיות "full", "low_stock" או "high_value", ו-threshold_value הוא מספר (למשל, "low_stock,10")

המשימה שלך היא:

  1. השתמש באותו מבנה Product משיעורים קודמים, עם השדות Price (float64) ו-Quantity (int)
  2. נתח את הקלט הראשון על ידי פיצול לפי פסיקים כדי לקבל רשומות נפרדות של מוצרים קיימים
  3. עבור כל רשומה של מוצר קיים, פצל לפי נקודתיים כדי לקבל את שם המוצר, המחיר והכמות
  4. המר את מחרוזת המחיר ל-float64 ואת מחרוזת הכמות ל-int
  5. צור ואכלס את המפה inventory בנתוני המוצרים הקיימים
  6. צור פונקציה בשם generateReport שמקבלת כפרמטרים את מפת המלאי, את סוג הדוח ואת ערך הסף
  7. נתח את הקלט השני על ידי פיצול לפי פסיקים כדי לקבל את סוג הדוח ואת ערך הסף
  8. המר את מחרוזת ערך הסף ל-float64
  9. הצג את כותרת הדוח בהתאם לסוג הדוח:
    • עבור "full": "=== FULL INVENTORY REPORT ==="
    • עבור "low_stock": "=== LOW STOCK REPORT ==="
    • עבור "high_value": "=== HIGH VALUE REPORT ==="
  10. הצג נתונים סטטיסטיים כלליים על המלאי:
    • "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. סנן והצג מוצרים בהתאם לסוג הדוח:
    • עבור "full": הצג את כל המוצרים
    • עבור "low_stock": הצג רק מוצרים שכמותם קטנה מערך הסף או שווה לו
    • עבור "high_value": הצג רק מוצרים שהערך הכולל שלהם (מחיר × כמות) גדול מערך הסף או שווה לו
  12. הצג את מקטע המוצרים המסוננים:
    • עבור "full": "All Products:"
    • עבור "low_stock": "Products with stock ≤ [threshold_value]:"
    • עבור "high_value": "Products with value ≥ $[threshold_value]:"
  13. עבור כל מוצר מסונן (בסדר אלפביתי לפי שם המוצר):
    • "- [product_name]: $[price] × [quantity] = $[total_value]"
  14. הצג נתונים סטטיסטיים עבור המוצרים המסוננים:
    • "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. מצא והצג את המוצרים היקרים ביותר והזולים ביותר:
    • "Price Analysis:"
    • "Most expensive: [product_name] at $[price]"
    • "Least expensive: [product_name] at $[price]"
  16. מצא והצג את המוצרים עם המלאי הגבוה ביותר והנמוך ביותר:
    • "Stock Analysis:"
    • "Highest stock: [product_name] with [quantity] units"
    • "Lowest stock: [product_name] with [quantity] units"
  17. הצג הערכת מצב של המלאי:
    • ספור מוצרים שכמותם ≤ 5: "Low stock items (≤5): [count]"
    • ספור מוצרים שכמותם > 20: "High stock items (>20): [count]"
    • ספור מוצרים שערכם ≥ $500: "High value items (≥$500): [count]"
  18. הצג את השלמת הדוח:
    • "Report generated successfully"
    • "Threshold applied: [threshold_value]"

השתמש בחבילת strings כדי לפצל את מחרוזות הקלט, בחבילת strconv כדי להמיר מחרוזות למספרים, בחבילת fmt לפלט מעוצב ובחבילת sort כדי למיין את שמות המוצרים בסדר אלפביתי. עצב את כל המחירים והערכים עם 2 ספרות אחרי הנקודה העשרונית. בעת מציאת המוצרים היקרים ביותר או הזולים ביותר, או המוצרים עם המלאי הגבוה ביותר או הנמוך ביותר, אם יש תיקו, השתמש בשם המוצר שמופיע ראשון בסדר אלפביתי. האתגר הזה מדגים כיצד ליצור מערכות דיווח מקיפות שמספקות תובנות עסקיות חשובות באמצעות ניתוח נתונים והצגה מעוצבת.

נסו בעצמכם

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")
	}
}

כל השיעורים ביחידה לוגיקה וזרימת התוכנית

תרגלו בעצמכם: קומפיילר Go אונליין