LoginSignup
0
0

More than 1 year has passed since last update.

Kotlin KoansでKotlin入門 第28回:Sum

Posted at

はじめに

公式の問題集「Kotlin Koans」を解きながらKotlinを学習します。

過去記事はこちら

問題

Sum

ある顧客が注文したすべての商品の価格の合計である、顧客が費やした金額の合計を計算する関数を実装しなさい。
各製品は注文された回数だけカウントされることに注意せよ。

修正前コード.kt
// Return the sum of prices for all the products ordered by a given customer
fun moneySpentBy(customer: Customer): Double =
        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
}

問題のポイント

数値の集まりにsumを使うか、sumOfを使って、まず要素を数値に変換してから合計します。

listOf(1, 5, 3).sum() == 9
listOf("a", "b", "cc").sumOf { it.length } == 4

ProductのpriceをsumOfを使って合計するために、ordersでそれぞれ保持しているproductsをflatMapを使って1つのリストにまとめます。

flatmap.kt
val list = listOf("123", "45")
println(list.flatMap { it.toList() }) // [1, 2, 3, 4, 5]

解答例

fun moneySpentBy(customer: Customer): Double =
        customer.orders.flatMap { it.products }.{ it.price }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0