보고서 생성하기
Coddy GO 여정의 로직 & 흐름 섹션에 포함된 레슨 — 68개 중 49번째.
챌린지
쉬움현재 재고에 대한 상세한 통찰력을 제공하는 포괄적인 보고서 기능을 구현하여 재고 관리 시스템을 완성하세요. 이 챌린지는 이전의 모든 기능을 기반으로 하며, 통계, 분류 및 분석이 포함된 형식화된 보고서를 생성하는 기능을 추가합니다.
두 개의 입력을 받게 됩니다:
"product1:price1:quantity1,product2:price2:quantity2,product3:price3:quantity3"형식의 기존 재고 데이터를 포함하는 문자열 (예:"Laptop:999.99:5,Mouse:25.50:15,Keyboard:75.00:8")"report_type,threshold_value"형식의 보고서 구성을 포함하는 문자열. 여기서 report_type은"full","low_stock", 또는"high_value"가 될 수 있으며 threshold_value는 숫자입니다 (예:"low_stock,10")
당신의 과제는 다음과 같습니다:
- 이전 레슨에서 사용한 것과 동일하게
Price(float64) 및Quantity(int) 필드를 가진Product구조체를 사용합니다. - 첫 번째 입력을 쉼표로 분리하여 개별 기존 제품 항목을 가져와 파싱합니다.
- 각 기존 제품 항목에 대해 콜론을 기준으로 분리하여 제품 이름, 가격, 수량을 가져옵니다.
- 가격 문자열을 float64로, 수량 문자열을 int로 변환합니다.
- 기존 제품 데이터로
inventory맵을 생성하고 채웁니다. - inventory 맵, 보고서 유형, 임계값을 매개변수로 받는
generateReport함수를 생성합니다. - 두 번째 입력을 쉼표로 분리하여 보고서 유형과 임계값을 가져와 파싱합니다.
- 임계값 문자열을 float64로 변환합니다.
- 보고서 유형에 따라 보고서 헤더를 표시합니다:
"full"인 경우:"=== FULL INVENTORY REPORT ===""low_stock"인 경우:"=== LOW STOCK REPORT ===""high_value"인 경우:"=== HIGH VALUE REPORT ==="
- 일반 재고 통계를 표시합니다:
"Total Products: [total_number_of_products]""Total Items in Stock: [sum_of_all_quantities]""Total Inventory Value: $[sum_of_price_times_quantity_for_all_products]""Average Product Price: $[total_inventory_value_divided_by_total_items]"
- 보고서 유형에 따라 제품을 필터링하고 표시합니다:
"full"인 경우: 모든 제품 표시"low_stock"인 경우: 수량이 임계값보다 작거나 같은 제품만 표시"high_value"인 경우: 총 가치(가격 × 수량)가 임계값보다 크거나 같은 제품만 표시
- 필터링된 제품 섹션을 표시합니다:
"full"인 경우:"All Products:""low_stock"인 경우:"Products with stock ≤ [threshold_value]:""high_value"인 경우:"Products with value ≥ $[threshold_value]:"
- 각 필터링된 제품에 대해 (제품 이름 기준 알파벳 순으로):
"- [product_name]: $[price] × [quantity] = $[total_value]"
- 필터링된 통계를 표시합니다:
"Filtered Results:""Products shown: [number_of_products_in_filtered_results]""Items in filtered products: [sum_of_quantities_for_filtered_products]""Value of filtered products: $[sum_of_values_for_filtered_products]"
- 가장 비싼 제품과 가장 저렴한 제품을 찾아 표시합니다:
"Price Analysis:""Most expensive: [product_name] at $[price]""Least expensive: [product_name] at $[price]"
- 재고가 가장 많은 제품과 가장 적은 제품을 찾아 표시합니다:
"Stock Analysis:""Highest stock: [product_name] with [quantity] units""Lowest stock: [product_name] with [quantity] units"
- 재고 상태 평가를 표시합니다:
- 수량이 5 이하인 제품 수:
"Low stock items (≤5): [count]" - 수량이 20 초과인 제품 수:
"High stock items (>20): [count]" - 가치가 $500 이상인 제품 수:
"High value items (≥$500): [count]"
- 수량이 5 이하인 제품 수:
- 보고서 완료를 표시합니다:
"Report generated successfully""Threshold applied: [threshold_value]"
입력 문자열을 분리하기 위해 strings 패키지를, 문자열을 숫자로 변환하기 위해 strconv 패키지를, 형식화된 출력을 위해 fmt 패키지를, 제품 이름을 알파벳 순으로 정렬하기 위해 sort 패키지를 사용하세요. 모든 가격과 가치는 소수점 둘째 자리까지 표시합니다. 가장 비싼/저렴한 제품 또는 재고가 가장 많은/적은 제품을 찾을 때 동률이 발생하면 알파벳 순으로 앞서는 제품 이름을 사용하세요. 이 챌린지는 데이터 분석 및 형식화된 프레젠테이션을 통해 가치 있는 비즈니스 통찰력을 제공하는 포괄적인 보고 시스템을 만드는 방법을 보여줍니다.
직접 해보기
package main
import (
"errors"
"fmt"
"sort"
"strconv"
"strings"
)
type Product struct {
Price float64
Quantity int
}
func updateStock(inventory map[string]Product, productName string, change int) error {
product, exists := inventory[productName]
if !exists {
return errors.New("product not found: " + productName)
}
newQuantity := product.Quantity + change
if newQuantity < 0 {
return fmt.Errorf("insufficient stock: cannot reduce %s by %d, only %d available", productName, -change, product.Quantity)
}
product.Quantity = newQuantity
inventory[productName] = product
return nil
}
func main() {
var inventoryData string
var updateRequests string
fmt.Scanln(&inventoryData)
fmt.Scanln(&updateRequests)
// Parse existing inventory
inventory := make(map[string]Product)
inventoryEntries := strings.Split(inventoryData, ",")
for _, entry := range inventoryEntries {
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 update requests
updateEntries := strings.Split(updateRequests, ",")
fmt.Println("Processing Stock Updates:")
totalUpdates := len(updateEntries)
successfulUpdates := 0
failedUpdates := 0
var failedProducts []string
for _, update := range updateEntries {
parts := strings.Split(update, ":")
productName := parts[0]
change, _ := strconv.Atoi(parts[1])
err := updateStock(inventory, productName, change)
if err != nil {
fmt.Printf("%s: Update failed - %s\n", productName, err.Error())
failedUpdates++
failedProducts = append(failedProducts, productName)
} else {
newQuantity := inventory[productName].Quantity
if change > 0 {
fmt.Printf("%s: Added %d units - New stock: %d\n", productName, change, newQuantity)
} else if change < 0 {
fmt.Printf("%s: Removed %d units - New stock: %d\n", productName, -change, newQuantity)
} else {
fmt.Printf("%s: No change - Current stock: %d\n", productName, newQuantity)
}
successfulUpdates++
}
}
// Update summary
fmt.Println("Update Summary:")
fmt.Printf("Updates processed: %d\n", totalUpdates)
fmt.Printf("Updates successful: %d\n", successfulUpdates)
fmt.Printf("Updates failed: %d\n", failedUpdates)
// Display updated inventory in alphabetical order
fmt.Println("Updated 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)
}
// Calculate final statistics
totalProducts := len(inventory)
totalItems := 0
totalValue := 0.0
for _, product := range inventory {
totalItems += product.Quantity
totalValue += product.Price * float64(product.Quantity)
}
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 failed updates
if len(failedProducts) > 0 {
fmt.Printf("Failed updates: %s\n", strings.Join(failedProducts, ","))
} else {
fmt.Println("All stock updates were processed successfully")
}
}