1

私は最近 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)
}

-- ヘルプやヒントは、ここで大いに役立ちます:)

4

2 に答える 2

2

数字をグループ化し、結果のリストを取得し、それぞれに含まれるペアの数を合計することで、これを行うことができました。

fun sockMerchant(n: Int, pile: Array<Int>): Int =
    pile.groupBy { it }.values.sumBy { it.size / 2 }

を実行するpile.groupBy { it }と、次の構造が得られます。

{10=[10, 10, 10, 10], 20=[20, 20, 20], 30=[30], 50=[50]}

値を取得し、それぞれのサイズを 2 で割って合計します。これにより、ハーフ ペアは 0 に、フル ペアはそれぞれ 1 に丸められます。

注:nこの場合の の目的は完全にはわかりません。

于 2020-10-04T15:09:50.977 に答える