Menu
CoddyTech

요약 - 동적 리스트

Coddy GO 여정의 기초 섹션에 포함된 레슨. 109개 중 83번째.

challenge icon

챌린지

중급

간단한 쇼핑 목록 관리자를 만들며 Go에서 슬라이스를 다루는 연습을 해 봅시다!

여러분의 과제는 쇼핑 목록을 조작하는 다음 함수들을 구현하는 것입니다.

  1. addItems: 쇼핑 목록에 새 항목 추가
  2. removeItem: 인덱스로 목록에서 항목 제거
  3. findExpensiveItems: 가격이 기준값을 초과하는 항목 찾기
  4. calculateTotalCost: 모든 항목의 총비용 계산

쇼핑 목록의 각 항목은 문자열(이름)과 float64(가격)로 표현됩니다. main 함수는 이 모든 작업이 함께 작동하는 모습을 보여 줍니다.

직접 해보기

package main

import "fmt"

// addItems는 새 항목과 해당 가격을 쇼핑 목록에 추가합니다
func addItems(names []string, prices []float64, newNames []string, newPrices []float64) ([]string, []float64) {
	// 여기에 코드를 작성하세요
	return names, prices
}

// removeItem은 지정된 인덱스의 항목을 제거합니다
func removeItem(names []string, prices []float64, index int) ([]string, []float64) {
	// 여기에 코드를 작성하세요
	return names, prices
}

// findExpensiveItems는 가격이 기준값을 초과하는 항목을 반환합니다
func findExpensiveItems(names []string, prices []float64, threshold float64) []string {
	// 여기에 코드를 작성하세요
	return nil
}

// calculateTotalCost는 모든 가격의 합계를 반환합니다
func calculateTotalCost(prices []float64) float64 {
	// 여기에 코드를 작성하세요
	return 0
}

func main() {
	// 빈 쇼핑 목록을 초기화합니다
	names := []string{}
	prices := []float64{}
	
	// 초기 항목을 추가합니다
	initialNames := []string{"Apples", "Milk", "Bread"}
	initialPrices := []float64{2.99, 3.49, 2.29}
	
	names, prices = addItems(names, prices, initialNames, initialPrices)
	
	// 초기 쇼핑 목록을 출력합니다
	fmt.Println("Initial Shopping List:")
	for i := range names {
		fmt.Printf("%d. %s - $%.2f\n", i, names[i], prices[i])
	}
	
	// 총비용을 계산하고 출력합니다
	total := calculateTotalCost(prices)
	fmt.Printf("\nTotal Cost: $%.2f\n", total)
	
	// 비싼 항목을 찾아 출력합니다
	priceThreshold := 3.00
	expensiveItems := findExpensiveItems(names, prices, priceThreshold)
	
	fmt.Printf("\nExpensive Items (above $%.2f):\n", priceThreshold)
	for _, item := range expensiveItems {
		fmt.Println(item)
	}
	
	// 새 항목을 추가합니다
	names, prices = addItems(names, prices, []string{"Cheese"}, []float64{4.99})
	
	// 항목을 제거합니다
	names, prices = removeItem(names, prices, 1)
	fmt.Println("\nRemoved item at index 1")
	
	// 최종 장보기 목록 출력
	fmt.Println("\nFinal Shopping List:")
	for i := range names {
		fmt.Printf("%d. %s - $%.2f\n", i, names[i], prices[i])
	}
}

기초의 모든 레슨

직접 연습해 보세요: 온라인 Go 컴파일러