문제

Learn about collection ordering and the the difference between operations in-place on mutable collections and operations returning new collections.

Implement a function for returning the list of customers, sorted in descending order by the number of orders they have made. Use sortedDescending or sortedByDescending.

val strings = listOf("bbb", "a", "cc")
strings.sorted() ==
        listOf("a", "bbb", "cc")

strings.sortedBy { it.length } ==
        listOf("a", "cc", "bbb")

strings.sortedDescending() ==
        listOf("cc", "bbb", "a")

strings.sortedByDescending { it.length } ==
        listOf("bbb", "cc", "a")

Task.kt

// Return a list of customers, sorted in the descending by number of orders they have made
fun Shop.getCustomersSortedByOrders(): List<Customer> =
        TODO()

Shop.kt

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 a list of customers, sorted in the descending by number of orders they have made
fun Shop.getCustomersSortedByOrders(): List<Customer> =
        customers.sortedByDescending { it.orders.size }

풀이

주문 횟수에 따라 내림차순으로 정렬된 고객 리스트를 반환하는 함수를 구현하는 문제이다.

문제에서 sortedDescending 또는 sortedByDescending을 사용하여 정렬을 하도록 했다.

똑같아 보이지만 두 함수는 약간의 차이가 존재한다.

sortedDescending 은 말그대로 내림차순 정렬을 해준다.

sortedByDescending지정값을 기준으로 정렬을 해준다. 즉, 조건이 들어가는 것이다.

먼저 Customer 클래스는 List<Order> 주문 목록을 가지고 있다.

Order 클래스에는 List<Product> 상품 목록이 존재한다.

우리는 주문 1건에 몇개의 상품이 있는지가 아니고, 주문 횟수만 파악하면 되기 때문에

결과적으로 orders의 크기를 확인하고 이를 토대로 내림차순으로 정렬 해주면 된다.

profile
개발하는 다람쥐

0개의 댓글

관련 채용 정보