마무리: 원장 프로그램 이식하기
Coddy의 C++ 개발자를 위한 Dart 코스 레슨. 48개 중 47번째.
챌린지
쉬움소스 참고 프로그램을 포팅하세요. Ledger()와 bool change(String name,int delta), int? get(String name), List<String> report()를 구현하세요. 변경할 때 이름이 없으면 잔액은 0부터 시작하며, 결과 잔액이 음수가 되면 변경하지 않고 거부하세요. 값이 0인 변경도 성공하면 항목을 생성합니다. 양수 잔액만 이름순으로 name=value 형식으로 보고하세요. 입력 줄은 add name delta, get name 또는 report이며, 이름은 ASCII 문자로 이루어지고 부호가 있는 정수의 합은 백만을 넘지 않습니다. 각 add는 소문자 불리언 텍스트를 출력하고, get은 값 또는 missing을 출력하며, report는 쉼표로 구분된 항목 또는 empty를 출력합니다. 명령이 없으면 empty를 출력하세요. 공개 API를 각각 독립적으로 사용할 수 있도록 하세요.
편집 가능한 파일에서 출력하지 마세요. 제공된 exercise.dart는 입력을 파싱하고 출력을 반환합니다. 잠긴 드라이버는 공개 API를 독립적으로 테스트하고 결과 뒤에 줄바꿈을 하나 붙여 출력합니다.
코드는 Ledger.dart, exercise.dart에 작성하세요. main.dart에는 제공된 입출력 코드가 있으며 수정할 수 없습니다.
C++ 참고 프로그램 전체:
#include <iostream>
#include <map>
#include <optional>
#include <sstream>
#include <string>
#include <vector>
class Ledger {
std::map<std::string, int> balances;
public:
bool change(const std::string& name, int delta) {
auto it = balances.find(name);
int value = (it == balances.end() ? 0 : it->second) + delta;
if (value < 0) return false;
balances[name] = value;
return true;
}
std::optional<int> get(const std::string& name) const {
auto it = balances.find(name);
if (it == balances.end()) return std::nullopt;
return it->second;
}
std::vector<std::string> report() const {
std::vector<std::string> out;
for (const auto& [name, value] : balances)
if (value > 0) out.push_back(name + "=" + std::to_string(value));
return out;
}
};
std::string join(const std::vector<std::string>& parts, const std::string& sep) {
std::string s;
for (size_t i = 0; i < parts.size(); ++i) s += (i ? sep : "") + parts[i];
return s;
}
int main() {
Ledger ledger;
std::vector<std::string> out;
std::string line;
while (std::getline(std::cin, line)) {
std::istringstream in(line);
std::vector<std::string> a;
for (std::string w; in >> w;) a.push_back(w);
if (a.empty()) continue;
if (a[0] == "add") {
out.push_back(ledger.change(a[1], std::stoi(a[2])) ? "true" : "false");
} else if (a[0] == "get") {
auto n = ledger.get(a[1]);
out.push_back(n ? std::to_string(*n) : "missing");
} else {
auto r = ledger.report();
out.push_back(r.empty() ? "empty" : join(r, ","));
}
}
std::cout << (out.empty() ? "empty" : join(out, "\n")) << "\n";
}
직접 해보기
import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Ledger.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
final l=Ledger();check(l.change('a',4)&&!l.change('a',-5)&&l.get('a')==4);check(l.change('z',0)&&l.get('z')==0&&l.get('missing')==null);check(l.report().join(',')=='a=4');
stdout.writeln(solve(input));
}
C++ 개발자를 위한 Dart의 모든 레슨
직접 연습해 보세요: 온라인 Dart 컴파일러