結果

問題 No.5 数字のブロック
ユーザー yo-kondo
提出日時 2018-03-06 22:24:35
言語 Kotlin
(2.1.0)
結果
AC  
実行時間 450 ms / 5,000 ms
コード長 1,590 bytes
コンパイル時間 12,670 ms
コンパイル使用メモリ 432,112 KB
実行使用メモリ 62,872 KB
最終ジャッジ日時 2024-11-20 13:59:41
合計ジャッジ時間 25,265 ms
ジャッジサーバーID
(参考情報)
judge1 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 34
権限があれば一括ダウンロードができます
コンパイルメッセージ
Main.kt:5:10: warning: parameter 'args' is never used
fun main(args: Array<String>) {
         ^
Main.kt:21:30: warning: parameter 'blockNum' is never used
fun block(boxWidth: String?, blockNum: String?, blockWidth: String?): String {
                             ^
Main.kt:25:9: warning: name shadowed: boxWidth
    val boxWidth = boxWidth?.toInt() ?: 0
        ^
Main.kt:29:9: warning: name shadowed: blockWidth
    val blockWidth = blockWidth
        ^

ソースコード

diff #

/**
 * エントリポイント
 * @param args コマンドライン引数
 */
fun main(args: Array<String>) {

    // readLine で標準入力から文字列を取得します。
    val l = readLine()
    val n = readLine()
    val w = readLine()

    println(block(l, n, w))
}

/**
 * 箱に入るブロックの数を計算して返します。
 * @param boxWidth 箱の幅
 * @param blockNum ブロックの数
 * @param blockWidth 各ブロックの幅
 */
fun block(boxWidth: String?, blockNum: String?, blockWidth: String?): String {

    // ?. でnullでない場合のみ後ろのメソッドを実行します。?. でメソッドを呼んだ場合は nullable が返ります。
    // ?: (エルビス演算子)でnullの場合に右の値を返します。これで nullable から not null になります。
    val boxWidth = boxWidth?.toInt() ?: 0

    // map で List<String> を List<Int> に変換します。
    // emptyList で空のListを返します。
    val blockWidth = blockWidth
            ?.split(" ")
            ?.map { it.toInt() }
            ?: emptyList()

    var inBlockNum = 0
    var inBlockWidth = 0

    // sorted で List をソートします。 sortedDescending で降順にソートします。
    val sortBlockWidth = blockWidth.sorted()

    // 小さいブロックから数えて、箱の幅を超えたら終了
    for (i in sortBlockWidth) {
        if (i + inBlockWidth <= boxWidth) {
            inBlockNum++
            inBlockWidth += i
        } else {
            break
        }
    }

    return inBlockNum.toString()
}
0