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 אונליין