Menu
CoddyTech

النهائي: سجل المخزون

الدرس 47 من 48 في دورة R لمطوري C++ على Coddy.

challenge icon

التحدي

سهل

نفّذ summarize(rows). كل صف عبارة عن اسم عنصر بأحرف ASCII صغيرة وكمية صحيحة موجبة أو سالبة، يفصل بينهما فراغ واحد. اجمع الكميات حسب الاسم؛ واحتفظ بالمجاميع الموجبة فقط؛ ورتّب الأسماء ترتيبًا معجميًا؛ وأعِد إدخالات بالصيغة name:total مفصولة بأسطر جديدة، أو empty إذا لم توجد أي إدخالات. الإدخال الفارغ صالح.

حافظ على واجهة API العامة المعلنة. يتحقق برنامج التشغيل المقفل الظاهر منها مباشرةً، كما يطبع solve(lines). تفي المدخلات بالعقد المحدد؛ وجميع العمليات الحسابية صغيرة ومحدودة.

ضع الكود في Functions.R وExercise.R. يستورد main.R التبعيات بالترتيب ويحتوي على كود الإدخال والإخراج المقدم؛ ولا يمكن تعديله.

انقل هذا المرجع الكامل المكتوب بلغة C++ إلى واجهة API العامة في R. وهو يطبّق العقد نفسه للمدخلات الصالحة.

#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
std::string summarize(const std::vector<std::string>& rows) {
    std::map<std::string,long long> totals;
    for (const auto& row : rows) {
        std::istringstream input(row);
        std::string name;
        long long amount;
        input >> name >> amount;
        totals[name] += amount;
    }
    std::ostringstream result;
    bool found=false;
    for (const auto& entry : totals) if (entry.second>0) {
        if (found) result << '\n';
        result << entry.first << ':' << entry.second;
        found=true;
    }
    return found ? result.str() : "empty";
}
int main() {
    std::vector<std::string> rows;
    std::string line;
    while (std::getline(std::cin,line)) rows.push_back(line);
    std::cout << summarize(rows) << '\n';
}

جرّب بنفسك

source("Functions.R")
source("Exercise.R")
stopifnot(identical(summarize(c("q 9","q -2","b 1")),"b:1\nq:7"))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")

جميع دروس R لمطوري C++

تدرّب بنفسك: مترجم R عبر الإنترنت