開発環境
- macOS Mojave - Apple (OS)
- Windows 10 Pro (OS)
- IntelliJ IDEA CE(Community Edition) (IDE(統合開発環境))
- Kotlin (プログラミング言語)
Head First Kotlin: A Brain-Friendly Guide (Dawn Griffiths(著)、David Griffiths(著)、O'Reilly Media)のChapter 12(built-in higher-order functions - Power Up Your Code)、Pool Puzzle(379)の解答を求めてみる。
コード
abstract class Pet(var name: String) class Cat(name: String) : Pet(name) class Dog(name: String) : Pet(name) class Fish(name: String) : Pet(name) class Contest<T : Pet>() { var scores: MutableMap<T, Int> = mutableMapOf() fun addScore(t: T, score: Int = 0) { if (score >= 0) scores.put(t, score) } fun getWinners(): Set<T> { val highScore = scores.values.max() val winners = scores.filter { it.value == highScore }.keys winners.forEach { println("Winner: ${it.name}") } return winners } } fun main() { val cat1 = Cat("Cat1") val cat2 = Cat("Cat2") val dog1 = Dog("Dog1") val dog2 = Dog("Dog2") val fish1 = Fish("Fish1") val fish2 = Fish("Fish2") val contest = Contest<Pet>() for (n in 1..5) { println("第${n}回") listOf(cat1, cat2, dog1, dog2, fish1, fish2) .forEach({ contest.addScore(it, kotlin.random.Random.nextInt(5)) }) val winners = contest.getWinners() contest.scores.forEach { println("${it.key.name} ${it.value}") } } }
入出力結果
第1回 Winner: Cat2 Winner: Fish1 Cat1 3 Cat2 4 Dog1 2 Dog2 2 Fish1 4 Fish2 2 第2回 Winner: Cat1 Winner: Cat2 Winner: Dog2 Winner: Fish1 Cat1 4 Cat2 4 Dog1 2 Dog2 4 Fish1 4 Fish2 0 第3回 Winner: Cat2 Winner: Fish1 Winner: Fish2 Cat1 2 Cat2 4 Dog1 3 Dog2 1 Fish1 4 Fish2 4 第4回 Winner: Cat2 Winner: Fish1 Cat1 2 Cat2 4 Dog1 2 Dog2 3 Fish1 4 Fish2 3 第5回 Winner: Fish2 Cat1 1 Cat2 1 Dog1 1 Dog2 0 Fish1 1 Fish2 3 Process finished with exit code 0
0 コメント:
コメントを投稿