Menu
Coddy logo textTech

בדיקת המלאי

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

challenge icon

אתגר

קל

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

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

  • מחרוזת שמכילה נתוני מלאי קיימים בפורמט "product1:price1:quantity1,product2:price2:quantity2,product3:price3:quantity3" (לדוגמה, "Laptop:999.99:5,Mouse:25.50:15,Keyboard:75.00:8")
  • מחרוזת שמכילה בקשות לבדיקת מלאי בפורמט "product1,product2,product3" (לדוגמה, "Mouse,Tablet,Keyboard")

המשימה שלכם היא:

  1. להשתמש באותו מבנה Product מהשיעור הקודם, עם השדות Price (float64) ו-Quantity (int)
  2. לנתח את הקלט הראשון באמצעות פיצול לפי פסיקים כדי לקבל רשומות מוצר נפרדות
  3. לכל רשומת מוצר, לפצל לפי נקודתיים כדי לקבל את שם המוצר, המחיר והכמות
  4. להמיר את מחרוזת המחיר ל-float64 ואת מחרוזת הכמות ל-int
  5. ליצור ולאכלס את מפת inventory בנתוני המוצרים שנותחו
  6. ליצור פונקציה בשם checkStock שמקבלת את מפת המלאי ושם מוצר כפרמטרים ומחזירה (int, error):
    • אם המוצר קיים במלאי, להחזיר את הכמות שלו ואת nil
    • אם המוצר אינו קיים, להחזיר 0 ושגיאה עם ההודעה "product not found: [product_name]"
  7. לנתח את הקלט השני באמצעות פיצול לפי פסיקים כדי לקבל את רשימת המוצרים לבדיקה
  8. להציג את הכותרת של בדיקת המלאי: "Stock Check Results:"
  9. עבור כל מוצר ברשימת הבדיקה, לקרוא לפונקציה checkStock ולהציג את התוצאות:
    • אם אין שגיאה: "[product_name]: [quantity] units in stock"
    • אם יש שגיאה: "[product_name]: Error - [error_message]"
  10. לספור ולהציג נתונים סטטיסטיים מסכמים:
    • "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. להציג את סך המלאי של המוצרים שנמצאו:
    • "Total stock for found products: [sum_of_quantities_for_existing_products] units"
  12. לפרט את המוצרים החסרים:
    • אם יש מוצרים חסרים: "Missing products: [comma_separated_list_of_missing_products]"
    • אם אין מוצרים חסרים: "All requested products are available"

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

נסו בעצמכם

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

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

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