Menu
CoddyTech

Portare un registro contabile in C++

Lezione 47 di 48 del corso JavaScript per sviluppatori C++ di Coddy.

challenge icon

Sfida

Facile

Porta l'algoritmo di riferimento C++ in JavaScript. L'input è un array di coppie [nome ASCII, quantità intera]. C++ usa una std::map ordinata con chiavi stringa e totali interi a 64 bit; JavaScript dovrebbe aggregare con Map e ordinare esplicitamente. Restituisci solo i totali positivi come coppie [nome,totale], nell'ordine dei nomi ASCII. Il programma C++ di supporto esegue tre casi di prova di riferimento.

Programma di riferimento in C++. Il programma completo analizza il contratto specificato per l'array di coppie JSON, inclusi i nomi ASCII con caratteri di escape, e stampa JSON.

#include <iostream>
#include <sstream>
#include <string>
#include <map>
#include <vector>
#include <cstdint>
#include <cctype>
#include <stdexcept>
#include <utility>

// This reader handles the stated array-of-pairs contract with ASCII names.
class Reader {
    std::string text;
    std::size_t pos=0;
    void whitespace() {
        while(pos<text.size() && std::isspace(static_cast<unsigned char>(text[pos]))) ++pos;
    }
    char take() {
        if(pos==text.size()) throw std::runtime_error("unexpected end");
        return text[pos++];
    }
    static unsigned hex(char c) {
        if(c>='0' && c<='9') return static_cast<unsigned>(c-'0');
        if(c>='a' && c<='f') return static_cast<unsigned>(c-'a'+10);
        if(c>='A' && c<='F') return static_cast<unsigned>(c-'A'+10);
        throw std::runtime_error("bad escape");
    }
public:
    explicit Reader(std::string input):text(std::move(input)) {}
    void token(char expected) {
        whitespace();
        if(take()!=expected) throw std::runtime_error("bad token");
    }
    bool next_is(char c) {
        whitespace();
        return pos<text.size() && text[pos]==c;
    }
    std::string name() {
        token('"');
        std::string result;
        for(;;) {
            unsigned value=static_cast<unsigned char>(take());
            if(value=='"') break;
            if(value=='\\') {
                switch(take()) {
                    case '"': value='"'; break;
                    case '\\': value='\\'; break;
                    case '/': value='/'; break;
                    case 'b': value='\b'; break;
                    case 'f': value='\f'; break;
                    case 'n': value='\n'; break;
                    case 'r': value='\r'; break;
                    case 't': value='\t'; break;
                    case 'u':
                        value=0;
                        for(int i=0;i<4;++i) value=value*16+hex(take());
                        break;
                    default: throw std::runtime_error("bad escape");
                }
            }
            if(value>127) throw std::runtime_error("non-ASCII name");
            result.push_back(static_cast<char>(value));
        }
        return result;
    }
    std::int64_t quantity() {
        whitespace();
        std::size_t consumed=0;
        double value=std::stod(text.substr(pos),&consumed);
        if(!(value>=-9007199254740991.0 && value<=9007199254740991.0))
            throw std::runtime_error("quantity out of bounds");
        auto integer=static_cast<std::int64_t>(value);
        if(static_cast<double>(integer)!=value) throw std::runtime_error("fractional quantity");
        pos+=consumed;
        return integer;
    }
    void finish() {
        whitespace();
        if(pos!=text.size()) throw std::runtime_error("extra input");
    }
};
static void print_name(const std::string& name) {
    const char *hex="0123456789abcdef";
    std::cout << '"';
    for(unsigned char c:name) {
        switch(c) {
            case '"': std::cout << "\\\""; break;
            case '\\': std::cout << "\\\\"; break;
            case '\b': std::cout << "\\b"; break;
            case '\f': std::cout << "\\f"; break;
            case '\n': std::cout << "\\n"; break;
            case '\r': std::cout << "\\r"; break;
            case '\t': std::cout << "\\t"; break;
            default:
                if(c<32) std::cout << "\\u00" << hex[c/16] << hex[c%16];
                else std::cout << static_cast<char>(c);
        }
    }
    std::cout << '"';
}
int main() {
    std::ostringstream input;
    input << std::cin.rdbuf();
    Reader reader(input.str());
    std::map<std::string,std::int64_t> totals;
    reader.token('[');
    if(!reader.next_is(']')) {
        do {
            reader.token('[');
            auto name=reader.name();
            reader.token(',');
            auto quantity=reader.quantity();
            reader.token(']');
            totals[name]+=quantity;
            if(!reader.next_is(',')) break;
            reader.token(',');
        } while(true);
    }
    reader.token(']');
    reader.finish();
    std::cout << '[';
    bool first=true;
    for(const auto& [name,total]:totals) {
        if(total<=0) continue;
        if(!first) std::cout << ',';
        first=false;
        std::cout << '[';
        print_name(name);
        std::cout << ',' << total << ']';
    }
    std::cout << "]\n";
}

L'input è un singolo valore JSON. Modifica i file sbloccati, iniziando da exercise.js. Il file visibile e bloccato driver.js chiama solve(input) e stampa il valore restituito come JSON compatto seguito da un carattere di nuova riga. Non aggiungere output diagnostico. I test confrontano l'output completo. Tutti i numeri in input e i totali interi calcolati rientrano nell'intervallo degli interi sicuri.

Input di esempio:

[["pen",3],["book",1],["pen",-1]]

Output previsto:

[["book",1],["pen",2]]

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 C++

Esercitati da solo: Compilatore JavaScript online