私は最近 HackerRank を始めて、「Sales by Match」を試みています。Kotlin の関数プログラミング機能を活用するという点で満足できるソリューションにたどり着きました。しかし、期待した答えが得られません...
問題の概要:
与えられた配列: -> ペアの総数を見つけて返します。
すなわち:
入力 -> [10, 20, 20, 10, 10, 30, 50, 10, 20]
ペア数 -> 3
ここに私のコードとそれを説明するいくつかのコメントがあります:
fun sockMerchant(n: Int, pile: Array<Int>): Int{
var count = 0
mutableMapOf<Int, Int>().withDefault { 0 }.apply {
// the [attempted] logic behind this piece of code here is
// that as we iterate through the list, the 'getOrPut()'
// function will return either the value for the given [key]
// or throw an exception if there is no such key
// in the map. However, since our map was created by
// [withDefault], the function resorts to its `defaultValue` <-> 0
// instead of throwing an exception.
for (e in values) {
// this simplifies our code and inserts a zero [+1] where needed.
// if (key exists)
// // return its associated value and MOD it:
// case: even -> increment counter
// else -> do nothing
// else if (key dne)
// // insert default value <-> [0] + 1
// ....
// ....
// ....
if (getOrPut(e, { getValue(e) + 1 } ) % 2 == 0) count++
}
}
return count
}
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val n = scan.nextLine().trim().toInt()
val ar = scan.nextLine().split(" ").map{ it.trim().toInt() }.toTypedArray()
val result = sockMerchant(n, ar)
println(result)
}
-- ヘルプやヒントは、ここで大いに役立ちます:)