
Learn about testing predicates and retrieving elements by condition.
Implement the following functions using all, any, count, find:
val numbers = listOf(-1, 0, 2)
val isZero: (Int) -> Boolean = { it == 0 }
numbers.any(isZero) == true
numbers.all(isZero) == false
numbers.count(isZero) == 1
numbers.find { it > 0 } == 2
// Return true if all customers are from a given city
fun Shop.checkAllCustomersAreFrom(city: City): Boolean =
TODO()
// Return true if there is at least one customer from a given city
fun Shop.hasCustomerFrom(city: City): Boolean =
TODO()
// Return the number of customers from a given city
fun Shop.countCustomersFrom(city: City): Int =
TODO()
// Return a customer who lives in a given city, or null if there is none
fun Shop.findCustomerFrom(city: City): Customer? =
TODO()
data class Shop(val name: String, val customers: List<Customer>)
data class Customer(val name: String, val city: City, val orders: List<Order>) {
override fun toString() = "$name from ${city.name}"
}
data class Order(val products: List<Product>, val isDelivered: Boolean)
data class Product(val name: String, val price: Double) {
override fun toString() = "'$name' for $price"
}
data class City(val name: String) {
override fun toString() = name
}
// Return true if all customers are from a given city
fun Shop.checkAllCustomersAreFrom(city: City): Boolean =
customers.all { it.city == city } == true
// Return true if there is at least one customer from a given city
fun Shop.hasCustomerFrom(city: City): Boolean =
customers.any { it.city == city } == true
// Return the number of customers from a given city
fun Shop.countCustomersFrom(city: City): Int =
customers.count { it.city == city }
// Return a customer who lives in a given city, or null if there is none
fun Shop.findCustomerFrom(city: City): Customer? =
customers.find { it.city == city }
컬렉션 함수인 all, any, count, find를 사용하여 특정 조건을 테스트하거나 조건에 맞는 요소를 찾는 방법을 바탕으로 주어진 함수를 구현하는 문제이다.
checkAllCustomersAreFrom은 모든 고객이 특정 도시에 거주하는 경우 true를 반환한다.hasCustomerFrom은 특정 도시에 거주하는 고객이 한 명 이상 있는지 확인한다.countCustomersFrom은 특정 도시에 거주하는 고객 수를 반환한다.findCustomerFrom은 특정 도시에 거주하는 고객을 반환하거나, 주어진 도시에 아무것도 없는 경우 null을 반환한다.요구사항 1
all 사용true요구사항 2
anytrue요구사항 3
count요구사항 4
findCustomer?로 반환(?은 null값을 허용해주기 때문에 따로 null 처리할 필요 없음)