/** * エントリポイント * @param args コマンドライン引数 */ fun main(args: Array) { // 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 を List に変換します。 // 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() }