세트 내 요소 확인하기
Coddy Dart 여정의 로직 & 흐름 섹션에 포함된 레슨. 65개 중 20번째.
Set을 다룰 때 컬렉션에 특정 요소가 있는지 확인해야 하는 경우가 많습니다. contains() 메서드를 사용하면 이를 간단하고 효율적으로 확인할 수 있으며, 요소를 찾으면 true를, 찾지 못하면 false를 반환합니다.
Set과 함께 contains()를 사용하는 주요 장점 중 하나는 뛰어난 성능입니다. 각 요소를 하나씩 확인해야 할 수 있는 List를 검색하는 것과 달리, Set 연산은 빠른 조회에 최적화되어 있어 컬렉션이 커도 contains()를 매우 효율적으로 사용할 수 있습니다.
Set<String> ingredients = {'flour', 'sugar', 'eggs', 'butter'};
// 특정 재료가 있는지 확인
bool hasFlour = ingredients.contains('flour');
bool hasMilk = ingredients.contains('milk');
print(hasFlour); // true
print(hasMilk); // false이 메서드는 데이터를 검증하거나, 전제 조건을 확인하거나, 특정 컬렉션에 포함되어 있는지를 기준으로 정보를 필터링해야 할 때 특히 유용합니다. 불리언 결과를 반환하므로 조건문과 논리 연산에서 사용하기에 적합합니다.
챌린지
쉬움
- 레시피 이름을 나타내는 문자열 입력을 읽습니다
- 식료품 저장실에 있는 재료를 나타내는 여러 문자열 입력을 읽습니다(
"pantry_done"을 입력하면 입력이 끝납니다) - 레시피에 필요한 재료를 나타내는 여러 문자열 입력을 읽습니다(
"recipe_done"을 입력하면 입력이 끝납니다) - 식료품 저장실에 있는 재료로 집합을 만듭니다
contains()메서드를 사용하여 필요한 각 재료가 식료품 저장실에 있는지 확인합니다- 아래에 표시된 정확한 형식으로 레시피 검증 결과를 출력합니다
예를 들어, 레시피 이름이 "Chocolate Chip Cookies"이고, 식료품 저장실에 있는 재료가 "flour", "sugar", "eggs", "butter", "vanilla"이며, 필요한 재료가 "flour", "sugar", "chocolate chips", "butter"라면 프로그램은 다음을 출력해야 합니다:
Recipe: Chocolate Chip Cookies
Pantry ingredients: {flour, sugar, eggs, butter, vanilla}
Required ingredients: [flour, sugar, chocolate chips, butter]
Checking ingredient availability:
- flour: Available
- sugar: Available
- chocolate chips: Missing
- butter: Available
Missing ingredients: [chocolate chips]
Status: Cannot make recipe - missing 1 ingredient(s)레시피 이름이 "Scrambled Eggs"이고, 식료품 저장실에 있는 재료가 "eggs", "butter", "salt", "pepper"이며, 필요한 재료가 "eggs", "butter", "salt"라면 프로그램은 다음을 출력해야 합니다:
Recipe: Scrambled Eggs
Pantry ingredients: {eggs, butter, salt, pepper}
Required ingredients: [eggs, butter, salt]
Checking ingredient availability:
- eggs: Available
- butter: Available
- salt: Available
Missing ingredients: []
Status: Ready to cook - all ingredients available레시피 이름이 "Fruit Salad"이고, 식료품 저장실에 있는 재료가 "apples", "bananas"이며, 필요한 재료가 "apples", "oranges", "grapes", "honey"라면 프로그램은 다음을 출력해야 합니다:
Recipe: Fruit Salad
Pantry ingredients: {apples, bananas}
Required ingredients: [apples, oranges, grapes, honey]
Checking ingredient availability:
- apples: Available
- oranges: Missing
- grapes: Missing
- honey: Missing
Missing ingredients: [oranges, grapes, honey]
Status: Cannot make recipe - missing 3 ingredient(s)프로그램은 식료품 저장실의 집합에 필요한 각 재료가 있는지 확인할 때 반드시 contains() 메서드를 사용해야 합니다. 확인 순서를 유지하도록 필요한 재료를 리스트에 저장하고, 누락된 재료는 별도의 리스트에 모으세요. 모든 재료를 사용할 수 있다면 상태로 "Ready to cook - all ingredients available"을 표시하세요. 재료가 하나라도 누락되었다면 누락된 재료의 개수를 X로 하여 "Cannot make recipe - missing X ingredient(s)"를 표시하세요.
직접 해보기
import 'dart:io';
void main() {
// 레시피 이름을 읽습니다
String? recipeName = stdin.readLineSync();
// "pantry_done"이 나올 때까지 보유 재료를 읽습니다
Set<String> pantryIngredients = <String>{};
String? pantryInput;
while ((pantryInput = stdin.readLineSync()) != "pantry_done") {
if (pantryInput != null) {
pantryIngredients.add(pantryInput);
}
}
// "recipe_done"이 나올 때까지 필요한 재료를 읽습니다
List<String> requiredIngredients = <String>[];
String? recipeInput;
while ((recipeInput = stdin.readLineSync()) != "recipe_done") {
if (recipeInput != null) {
requiredIngredients.add(recipeInput);
}
}
// TODO: 아래에 코드를 작성하세요
// pantryIngredients.contains()를 사용하여 필요한 재료를 각각 확인하세요
// 없는 재료를 저장할 리스트를 만드세요
// 재료가 있는지 확인하고 지정된 형식으로 결과를 출력하세요
// 결과를 출력하세요(직접 작성한 코드로 대체하세요)
print("Recipe: $recipeName");
print("Pantry ingredients: $pantryIngredients");
print("Required ingredients: $requiredIngredients");
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
로직 & 흐름의 모든 레슨
1고급 리스트 조작
리스트 속성: first 및 last리스트 상태: isEmpty 및 isNotEmpty리스트 뒤집기리스트에 추가: insert리스트 요소 제거: removeWhere리스트에서 찾기: indexOf리스트 정렬리스트 섞기요약 - 리스트 정리 도구직접 연습해 보세요: 온라인 Dart 컴파일러