Menu
Coddy logo textTech

עדכון כמות המלאי

חלק מהיחידה לוגיקה וזרימת התוכנית במסלול ה-GO של Coddy. שיעור 48 מתוך 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:change1,product2:change2,product3:change3", כאשר השינויים יכולים להיות מספרים שלמים חיוביים או שליליים (לדוגמה, "Mouse:10,Tablet:-5,Keyboard:-3")

המשימה שלכם:

  1. השתמשו באותו מבנה Product מהשיעורים הקודמים, עם השדות Price (float64) ו-Quantity (int)
  2. נתחו את הקלט הראשון באמצעות פיצול לפי פסיקים כדי לקבל את הרשומות של המוצרים הקיימים
  3. עבור כל רשומה של מוצר קיים, פצלו לפי נקודתיים כדי לקבל את שם המוצר, המחיר והכמות
  4. המירו את מחרוזת המחיר ל-float64 ואת מחרוזת הכמות ל-int
  5. צרו ואכלסו את המפה inventory בנתוני המוצרים הקיימים
  6. צרו פונקציה בשם updateStock שמקבלת את מפת המלאי, את שם המוצר ואת שינוי הכמות כפרמטרים ומחזירה שגיאה:
    • אם המוצר אינו קיים במלאי, החזירו שגיאה עם ההודעה "product not found: [product_name]"
    • אם שינוי הכמות יוביל למלאי שלילי (הכמות הנוכחית + השינוי < 0), החזירו שגיאה עם ההודעה "insufficient stock: cannot reduce [product_name] by [absolute_change_value], only [current_quantity] available"
    • אם העדכון תקין, שנו את כמות המוצר במלאי והחזירו nil
  7. נתחו את הקלט השני באמצעות פיצול לפי פסיקים כדי לקבל את רשימת בקשות עדכון המלאי
  8. עבור כל בקשת עדכון, פצלו לפי נקודתיים כדי לקבל את שם המוצר ואת שינוי הכמות
  9. המירו את מחרוזת שינוי הכמות ל-int
  10. הציגו את כותרת תהליך העדכון: "Processing Stock Updates:"
  11. עבור כל בקשת עדכון, קראו לפונקציה updateStock והציגו את התוצאות:
    • אם אין שגיאה והשינוי חיובי: "[product_name]: Added [change] units - New stock: [new_quantity]"
    • אם אין שגיאה והשינוי שלילי: "[product_name]: Removed [absolute_change_value] units - New stock: [new_quantity]"
    • אם אין שגיאה והשינוי הוא אפס: "[product_name]: No change - Current stock: [current_quantity]"
    • אם יש שגיאה: "[product_name]: Update failed - [error_message]"
  12. ספרו והציגו את נתוני העדכונים:
    • "Update Summary:"
    • "Updates processed: [total_number_of_updates_processed]"
    • "Updates successful: [number_of_successful_updates]"
    • "Updates failed: [number_of_failed_updates]"
  13. הציגו את המלאי המעודכן בסדר אלפביתי לפי שם המוצר:
    • "Updated Inventory:"
    • עבור כל מוצר: "- [product_name]: $[price] (Stock: [quantity])"
  14. חשבו והציגו את נתוני המלאי הסופיים:
    • "Final Inventory Statistics:"
    • "Total Products: [total_number_of_products_in_inventory]"
    • "Total Items in Stock: [sum_of_all_quantities]"
    • "Total Inventory Value: $[sum_of_price_times_quantity_for_all_products]"
  15. הציגו את העדכונים שנכשלו:
    • אם יש עדכונים שנכשלו: "Failed updates: [comma_separated_list_of_failed_product_names]"
    • אם אין עדכונים שנכשלו: "All stock updates were processed successfully"

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

נסו בעצמכם

package main

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

type Product struct {
	Price    float64
	Quantity int
}

func addNewItem(inventory map[string]Product, productName string, price float64, quantity int) error {
	if _, exists := inventory[productName]; exists {
		return errors.New("product already exists: " + productName)
	}
	inventory[productName] = Product{Price: price, Quantity: quantity}
	return nil
}

func main() {
	var existingInventory string
	var newProducts string
	fmt.Scanln(&existingInventory)
	fmt.Scanln(&newProducts)

	inventory := make(map[string]Product)

	// Parse existing inventory
	existingItems := strings.Split(existingInventory, ",")
	for _, item := range existingItems {
		parts := strings.Split(item, ":")
		name := parts[0]
		price, _ := strconv.ParseFloat(parts[1], 64)
		quantity, _ := strconv.Atoi(parts[2])
		inventory[name] = Product{Price: price, Quantity: quantity}
	}

	// Parse new products to add
	newItems := strings.Split(newProducts, ",")
	
	fmt.Println("Adding New Items:")
	
	itemsProcessed := 0
	itemsAdded := 0
	itemsRejected := 0
	var rejectedProducts []string

	for _, item := range newItems {
		parts := strings.Split(item, ":")
		name := parts[0]
		price, _ := strconv.ParseFloat(parts[1], 64)
		quantity, _ := strconv.Atoi(parts[2])
		
		itemsProcessed++
		
		err := addNewItem(inventory, name, price, quantity)
		if err != nil {
			fmt.Printf("%s: Failed to add - %s\n", name, err.Error())
			itemsRejected++
			rejectedProducts = append(rejectedProducts, name)
		} else {
			fmt.Printf("%s: Successfully added - $%.2f (Stock: %d)\n", name, price, quantity)
			itemsAdded++
		}
	}

	// Addition summary
	fmt.Println("Addition Summary:")
	fmt.Printf("Items processed: %d\n", itemsProcessed)
	fmt.Printf("Items added: %d\n", itemsAdded)
	fmt.Printf("Items rejected: %d\n", itemsRejected)

	// Display updated inventory in alphabetical order
	fmt.Println("Updated Inventory:")
	var productNames []string
	for name := range inventory {
		productNames = append(productNames, name)
	}
	sort.Strings(productNames)

	totalProducts := 0
	totalItems := 0
	totalValue := 0.0

	for _, name := range productNames {
		product := inventory[name]
		fmt.Printf("- %s: $%.2f (Stock: %d)\n", name, product.Price, product.Quantity)
		totalProducts++
		totalItems += product.Quantity
		totalValue += product.Price * float64(product.Quantity)
	}

	// Final inventory statistics
	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 rejected products
	if len(rejectedProducts) > 0 {
		fmt.Printf("Rejected products: %s\n", strings.Join(rejectedProducts, ","))
	} else {
		fmt.Println("All new products were added successfully")
	}
}

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

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