Menu
CoddyTech

הסבת מערכת המלאי

שיעור 47 מתוך 48 בקורס Luau למפתחי Rust של Coddy.

challenge icon

אתגר

בינוני

המירו את תוכנית הייחוס ב-Rust למודולים ב-Luau. כל שורת קלט היא שם באותיות ASCII קטנות, נקודתיים, והפרש שלם עם סימן. חשבו את הסכום לכל שם, השאירו רק סכומים סופיים חיוביים, מיינו את השמות בסדר עולה והחזירו רשומות name=total מחוברות בפסיקים. החזירו empty אם לא נותרו רשומות. ממשו את inventory.aggregate(lines) בקובץ inventory.luau; app מעצב את התוצאה. כל שורות הקלט תקינות.

תוכנית הייחוס ב-Rust

use std::collections::BTreeMap;
use std::io::{self, Read};
fn aggregate(input: &str) -> BTreeMap<String, i64> {
    let mut counts = BTreeMap::new();
    for line in input.lines() {
        let (name, delta) = line.split_once(':').unwrap();
        *counts.entry(name.to_owned()).or_insert(0) += delta.parse::<i64>().unwrap();
    }
    counts
}
fn main() {
    let mut input = String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    let rows: Vec<_> = aggregate(&input).into_iter()
        .filter(|(_, total)| *total > 0)
        .map(|(name, total)| format!("{}={}", name, total)).collect();
    println!("{}", if rows.is_empty() { "empty".to_owned() } else { rows.join(",") });
}

ערכו את app.luau, inventory.luau. הקובץ הנעול הגלוי main.luau קורא את stdin לרצף של שורות, קורא ל-app.run(lines) ומדפיס את הערך שהוחזר עם תו שורה חדשה אחד בסוף. אל תדפיסו הודעות אבחון ואל תשנו את שמות המודולים. קלט ריק יוצר רצף ריק. כל הערכים המספריים קטנים מספיק כדי למנוע גלישה.

בדיקות API ציבוריות: inventory.aggregate(lines) מחזירה טבלה חדשה של הפרשים חתומים שסוכמו, ומשאירה גם סכומים שערכם אפס. קלט ריק מחזיר טבלה ריקה. העיצוב והסינון מתבצעים ב-app. מנהל ההתקן הנעול בודק את ההתנהגות הזאת לפני הקריאה ל-app.run. בדיקות אלה אינן מדפיסות דבר כשהן מצליחות.

נסו בעצמכם

-- בדיקות של ה-API הציבורי
do
local inventory=require("./inventory")
local counts=inventory.aggregate({"pen:3","pen:-1","book:0"})
assert(counts.pen==2 and counts.book==0,"aggregate must sum signed deltas by name")
local empty=inventory.aggregate({})
assert(next(empty)==nil,"aggregate empty input returns an empty table")
assert(counts.pen==2,"aggregation calls retain independent result state")
end
local app = require("./app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))

כל השיעורים ביחידה Luau למפתחי Rust

תרגלו בעצמכם: קומפיילר Luau אונליין