Menu
CoddyTech

Kotlinの台帳を移植する

Coddyの「Kotlin開発者のためのJavaScript」コースのレッスン 47/48。

challenge icon

チャレンジ

簡単

付属のKotlin製台帳リファレンスをJavaScriptに移植してください。入力は[name, quantity]ペアのJSON配列です。名前に含まれるのはASCII文字のみです。数量は整数で、計算されるすべての合計はJavaScriptの安全な整数の範囲内に収まります。名前ごとにすべての更新を合計し、途中の負の合計も保持してください。集計後、正の合計のみを残し、名前をASCII順に並べて、[name, total]ペアを返してください。__proto__のような名前も通常のデータとして扱えるように、Mapを使用してください。集計前に更新をフィルターしてはいけません。

exercise.jsでsolveエクスポートを実装してください。ロックされているdriver.jsは標準入力を解析し、返されたデータをJSONとしてシリアライズして、最後に改行を付けて出力します。診断メッセージを出力してはいけません。以下の完全なソースリファレンスには独自の標準入力エントリーポイントがあります。JavaScriptのsolve関数は、提供されたドライバーにデータを返します。

Kotlinのリファレンス

// JSON input is restricted to an array of [ASCII name, integer quantity] pairs.
// Numeric tokens may use decimal or exponent notation when their value is integral.
class LedgerInput(private val text: String) {
    private var position = 0
    private fun whitespace() {
        while (position < text.length && text[position].isWhitespace()) position++
    }
    private fun take(character: Char) {
        whitespace()
        require(position < text.length && text[position] == character)
        position++
    }
    private fun has(character: Char): Boolean {
        whitespace()
        return position < text.length && text[position] == character
    }
    private fun string(): String {
        take('"')
        val out = StringBuilder()
        while (true) {
            val character = text[position++]
            if (character == '"') return out.toString()
            if (character != '\\') {
                out.append(character)
            } else {
                when (val escape = text[position++]) {
                    '"', '\\', '/' -> out.append(escape)
                    'b' -> out.append('\b')
                    'f' -> out.append('\u000C')
                    'n' -> out.append('\n')
                    'r' -> out.append('\r')
                    't' -> out.append('\t')
                    'u' -> {
                        out.append(text.substring(position, position + 4).toInt(16).toChar())
                        position += 4
                    }
                    else -> error("Invalid JSON escape")
                }
            }
        }
    }
    private fun integer(): Long {
        whitespace()
        val start = position
        while (position < text.length && text[position] !in ",] \t\r\n") position++
        return java.math.BigDecimal(text.substring(start, position)).longValueExact()
    }
    fun rows(): List<Pair<String, Long>> {
        val result = mutableListOf<Pair<String, Long>>()
        take('[')
        if (!has(']')) {
            while (true) {
                take('[')
                val name = string()
                take(',')
                val quantity = integer()
                take(']')
                result.add(name to quantity)
                if (!has(',')) break
                take(',')
            }
        }
        take(']')
        whitespace()
        require(position == text.length)
        return result
    }
}
fun quoteJson(value: String): String = buildString {
    append('"')
    for (character in value) {
        when (character) {
            '"' -> append("\\\"")
            '\\' -> append("\\\\")
            '\b' -> append("\\b")
            '\u000C' -> append("\\f")
            '\n' -> append("\\n")
            '\r' -> append("\\r")
            '\t' -> append("\\t")
            else -> if (character < ' ') {
                append("\\u" + character.code.toString(16).padStart(4, '0'))
            } else append(character)
        }
    }
    append('"')
}
fun solve(rows: List<Pair<String, Long>>): List<Pair<String, Long>> {
    val totals = mutableMapOf<String, Long>()
    for ((name, quantity) in rows) totals[name] = (totals[name] ?: 0L) + quantity
    return totals.keys.filter { totals.getValue(it) > 0L }.sorted().map { it to totals.getValue(it) }
}
fun main() {
    val rows = LedgerInput(readLine()!!).rows()
    val result = solve(rows).joinToString(separator=",", prefix="[", postfix="]") {
        (name, total) -> "[" + quoteJson(name) + "," + total + "]"
    }
    println(result)
}

自分で試してみよう

import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// stdin から JSON 値が1つ渡されます。データを返してください。solve 内で出力しないでください。
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));

Kotlin開発者のためのJavaScriptのすべてのレッスン

自分で練習してみよう: JavaScriptオンラインコンパイラ