Menu
Coddy logo textTech

הוספת פריט חדש

חלק מהיחידה לוגיקה וזרימת התוכנית במסלול ה-GO של Coddy. שיעור 47 מתוך 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:price1:quantity1,product2:price2:quantity2,product3:price3:quantity3" (לדוגמה, "Monitor:299.99:10,Mouse:19.99:20,Webcam:89.99:12")

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

  1. להשתמש באותו מבנה Product מהשיעורים הקודמים, עם השדות Price (float64) ו-Quantity (int)
  2. לנתח את הקלט הראשון באמצעות פיצול לפי פסיקים כדי לקבל רשומות של מוצרים קיימים בנפרד
  3. לכל רשומת מוצר קיימת, לפצל לפי נקודתיים כדי לקבל את שם המוצר, המחיר והכמות
  4. להמיר את מחרוזת המחיר ל-float64 ואת מחרוזת הכמות ל-int
  5. ליצור ולאכלס את המפה inventory בנתוני המוצרים הקיימים
  6. ליצור פונקציה בשם addNewItem שמקבלת את מפת המלאי, שם המוצר, המחיר והכמות כפרמטרים ומחזירה שגיאה:
    • אם המוצר כבר קיים במלאי, להחזיר שגיאה עם ההודעה "product already exists: [product_name]"
    • אם המוצר לא קיים, להוסיף אותו למלאי ולהחזיר nil
  7. לנתח את הקלט השני באמצעות פיצול לפי פסיקים כדי לקבל את רשימת המוצרים החדשים להוספה
  8. לכל רשומת מוצר חדש, לפצל לפי נקודתיים כדי לקבל את שם המוצר, המחיר והכמות
  9. להמיר את מחרוזת המחיר ל-float64 ואת מחרוזת הכמות ל-int
  10. להציג את כותרת תהליך ההוספה: "Adding New Items:"
  11. לכל מוצר חדש, לקרוא לפונקציה addNewItem ולהציג את התוצאות:
    • אם אין שגיאה: "[product_name]: Successfully added - $[price] (Stock: [quantity])"
    • אם יש שגיאה: "[product_name]: Failed to add - [error_message]"
  12. לספור ולהציג את נתוני ההוספה:
    • "Addition Summary:"
    • "Items processed: [total_number_of_items_processed]"
    • "Items added: [number_of_items_successfully_added]"
    • "Items rejected: [number_of_items_that_failed_to_add]"
  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. לפרט מוצרים שנדחו:
    • אם יש מוצרים שנדחו: "Rejected products: [comma_separated_list_of_rejected_products]"
    • אם לא נדחו מוצרים: "All new products were added successfully"

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

נסו בעצמכם

package main

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

type Product struct {
	Price    float64
	Quantity int
}

func checkStock(inventory map[string]Product, productName string) (int, error) {
	product, exists := inventory[productName]
	if !exists {
		return 0, errors.New("product not found: " + productName)
	}
	return product.Quantity, nil
}

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

	inventory := make(map[string]Product)

	// Parse inventory data
	productEntries := strings.Split(inventoryData, ",")
	for _, entry := range productEntries {
		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 check requests
	productsToCheck := strings.Split(checkRequests, ",")

	fmt.Println("Stock Check Results:")

	var productsFound int
	var productsNotFound int
	var totalStock int
	var missingProducts []string

	for _, productName := range productsToCheck {
		quantity, err := checkStock(inventory, productName)
		if err != nil {
			fmt.Printf("%s: Error - %s\n", productName, err.Error())
			productsNotFound++
			missingProducts = append(missingProducts, productName)
		} else {
			fmt.Printf("%s: %d units in stock\n", productName, quantity)
			productsFound++
			totalStock += quantity
		}
	}

	fmt.Println("Check Summary:")
	fmt.Printf("Products checked: %d\n", len(productsToCheck))
	fmt.Printf("Products found: %d\n", productsFound)
	fmt.Printf("Products not found: %d\n", productsNotFound)
	fmt.Printf("Total stock for found products: %d units\n", totalStock)

	if len(missingProducts) > 0 {
		fmt.Printf("Missing products: %s\n", strings.Join(missingProducts, ","))
	} else {
		fmt.Println("All requested products are available")
	}
}

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

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