Menu
Coddy logo textTech

新規アイテムの追加

CoddyのGOジャーニー「論理とフロー」セクションの一部 — レッスン 47/68。

challenge icon

チャレンジ

簡単

新しい製品を安全に追加する機能を実装することで、在庫管理システムを拡張しましょう。このチャレンジは、以前の在庫確認システムをベースにしており、適切なエラーハンドリングを通じて重複エントリを防ぎながら、在庫を拡大する機能を追加します。

2つの入力を受け取ります:

  • "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. 2番目の入力をカンマで分割して、追加する新しい製品のリストを取得し、解析します。
  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")
	}
}

論理とフローのすべてのレッスン