Menu
CoddyTech

C++の台帳を移植する

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

challenge icon

チャレンジ

簡単

C++の参照アルゴリズムをJavaScriptに移植してください。入力は[ASCII name,integer quantity]のペアの配列です。C++では文字列キーと64ビット整数の合計値を持つソート済みのstd::mapを使用します。JavaScriptではMapで集計し、明示的にソートしてください。正の合計値のみを[name,total]のペアとして、ASCII nameの順に返してください。対応するC++プログラムは、3つの参照用テストケースを実行します。

C++の参照プログラム。完全なプログラムは、エスケープされたASCII nameを含む、指定されたJSONのペア配列の形式を解析し、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";
}

入力は1つのJSON値です。編集可能なファイルを編集してください。まずexercise.jsから始めます。表示されているロック済みのdriver.jsはsolve(input)を呼び出し、その戻り値をコンパクトなJSONとして出力し、その後に改行を1つ出力します。診断用の出力を追加しないでください。テストでは出力全体を比較します。すべての数値入力と計算された整数の合計値は、安全な整数の範囲内に収まります。

入力例:

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

期待される出力:

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

自分で試してみよう

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)));

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

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