Menu
Coddy logo textTech

새 항목 추가하기

Coddy GO 여정의 로직 & 흐름 섹션에 포함된 레슨 — 68개 중 47번째.

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. 이전 레슨과 동일하게 Price (float64) 및 Quantity (int) 필드를 가진 Product 구조체를 사용합니다.
  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 패키지를 사용하세요. 모든 가격과 총 재고 가치는 소수점 둘째 자리까지 표시합니다. 이 챌린지는 적절한 에러 처리와 유효성 검사를 통해 중복 항목을 방지하면서 데이터 컬렉션을 안전하게 확장하는 방법을 보여줍니다.

직접 해보기

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

로직 & 흐름의 모든 레슨