0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Josh Skeen, David Greenhalgh著 『Kotlinプログラミング』 章末問題に挑戦(第19章)

Posted at

 Josh Skeen, David Greenhalgh著『Kotlinプログラミング』には章末問題がある。残念なことに解答がないので、第18章に引き続き本を読み進めながら答案を記述する。
 もし回答に間違いや意見があれば、ぜひご指摘いただきたい。

第19章 章末問題 回答案

19.6 チャレンジ! Mapのキーと値の関係を反転させる

 2つの方法でflipを行った。ひとつはMapの要素を直接入れ替える方法。もうひとつはMapをListに変換した後、それぞれの要素を入れ替える方法。
 以下に私の考えた方法を掲載しましたが、関数型プログラミングによるより良いコードをご教示いただきましたので、そちらを確認された方が良いと思います。次のアドレスをご参照ください。
【Kotlin備忘録】コレクション関数 map, filter + おまけ(generateSequence)
     (teratailでMapの使い方と関数型プログラミングについてにて質問し、教えていただきました。)
 また、Qiitaの質問コーナーで次のような方法のご教示も頂きました。
https://qiita.com/guijiu/questions/7508d9daf8e1b4ab73e4#answer-9bb0cc0f1f334fb4f333
https://qiita.com/guijiu/questions/7508d9daf8e1b4ab73e4#answer-56be38bf1c2ce2861bb8
さらに変数ですが、
https://qiita.com/guijiu/questions/7508d9daf8e1b4ab73e4#answer-ecbc8fc599945ffb7682
https://qiita.com/guijiu/questions/7508d9daf8e1b4ab73e4#answer-83d3713ecc38c149580b

また、型推論の書き方についてもアドバイス頂きましたのでご紹介します。
https://qiita.com/guijiu/items/b3a5b58317095561e1eb#comment-b8ee727206972b3e81de

fun main() {
    val gradesByStudent = mapOf("Josh" to 4.0, "Alex" to 2.0, "Jane" to 3.0)
    println(gradesByStudent)

    println("List方式flip:${flipValuesList(gradesByStudent)}")
    println("Map 方式flip:${flipValuesMap(gradesByStudent)}")

}

// Mapの要素を組み立てなおす方法
fun flipValuesMap(gradesByStudent: Map<String, Double>): Map<Double, String> {
    var abc: MutableMap<Double, String> = mutableMapOf()
    gradesByStudent.forEach { (k, v) ->
        abc.put(v, k)
    }
    return abc
}

// MapをListに直し、組み立てなおしMapに戻す方法
fun flipValuesList(gradesByStudent: Map<String, Double>): Map<Double, String> {
    var names: MutableList<String> = mutableListOf()
    var values: MutableList<Double> = mutableListOf()
    // gradesByStudentをリストに変化してからその要素nameとvalueを取り出し、それぞれをリストにする方法
    gradesByStudent.toList().forEach { names.add(it.first) }
    gradesByStudent.toList().forEach { values.add(it.second) }
    return values.zip(names).toMap()    // valuesにnamesを結合
}

19.7 チャレンジ! 関数型プログラミングをTavern.ktに法要

19.8 チャレンジ! スライディングウインドウ

(少し、無名関数、ラムダ式、型推論、関数型プログラミング辺りで息切れしてきたので、しばらく復習をしてから出直してきます。)

第2章チャレンジ!答案
第3章チャレンジ!答案
第4章チャレンジ!答案
第7章チャレンジ!答案
第8章チャレンジ!答案
第10章チャレンジ!答案
第13章チャレンジ!答案
第15章チャレンジ!答案
第18章チャレンジ!答案
第19章チャレンジ!答案

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?