Menu
CoddyTech

Adatta un registro contabile in Kotlin

Lezione 47 di 48 del corso JavaScript per sviluppatori Kotlin di Coddy.

challenge icon

Sfida

Facile

Porta il riferimento del registro in Kotlin fornito in JavaScript. L’input è un array JSON di coppie [name, quantity]. I nomi contengono solo caratteri ASCII; le quantità sono numeri interi e tutti i totali calcolati rientrano nell’intervallo degli interi sicuri di JavaScript. Somma ogni aggiornamento per nome, mantenendo i totali intermedi negativi. Dopo l’aggregazione, conserva solo i totali positivi, ordina i nomi secondo l’ordine ASCII e restituisci coppie [name, total]. Usa una Map affinché nomi come __proto__ rimangano dati ordinari. Non filtrare gli aggiornamenti prima dell’aggregazione.

Implementa l’esportazione solve in exercise.js. Il file bloccato driver.js analizza l’input standard e serializza i dati restituiti come JSON, con un carattere di nuova riga finale. Non stampare messaggi diagnostici. Il riferimento completo del codice sorgente qui sotto ha un proprio punto di ingresso per lo stdin; la tua funzione JavaScript solve restituisce i dati al driver fornito.

Riferimento 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)
}

Provalo tu

import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// Un valore JSON arriva su stdin. Restituisci i dati; non stampare nulla all'interno di solve.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));

Tutte le lezioni di JavaScript per sviluppatori Kotlin

Esercitati da solo: Compilatore JavaScript online