Menu
CoddyTech

C++ 장부 프로그램 포팅하기

Coddy의 C++ 개발자를 위한 JavaScript 코스 레슨. 48개 중 47번째.

challenge icon

챌린지

쉬움

C++ 참조 알고리즘을 JavaScript로 포팅하세요. 입력은 [ASCII 이름, 정수 수량] 쌍의 배열입니다. C++에서는 문자열 키와 64비트 정수 합계를 사용하는 정렬된 std::map을 사용합니다. JavaScript에서는 Map으로 합산하고 명시적으로 정렬해야 합니다. 양수인 합계만 [이름, 합계] 쌍으로 반환하며, ASCII 이름 순서로 정렬합니다. 함께 제공되는 C++ 프로그램은 참조용 테스트 픽스처 세 개를 실행합니다.

C++ 참조 프로그램입니다. 완전한 프로그램은 이스케이프된 ASCII 이름을 포함해 지정된 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";
}

입력은 JSON 값 하나입니다. 잠금 해제된 파일을 수정하되, exercise.js부터 시작하세요. 화면에 보이는 잠긴 driver.js는 solve(input)을 호출하고 반환값을 공백 없는 JSON으로 출력한 뒤 줄바꿈 하나를 덧붙입니다. 진단용 출력을 추가하지 마세요. 테스트에서는 전체 출력을 비교합니다. 모든 숫자 입력과 계산된 정수 합계는 안전한 정수 범위 안에 있습니다.

입력 예시:

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

예상 출력:

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

직접 해보기

import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// stdin으로 JSON 값 하나가 입력됩니다. 데이터를 반환하고, solve 내부에서는 출력하지 마세요.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));

C++ 개발자를 위한 JavaScript의 모든 레슨

직접 연습해 보세요: 온라인 JavaScript 컴파일러