Menu
CoddyTech

הסבה: פקודות מלאי

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

challenge icon

אתגר

בינוני

העבר את מימוש הייחוס ב-Go ל-Swift. ממש את Inventory() עם add(_ name: String, count: Int) -> Bool, take(_ name: String, count: Int) -> Bool, quantity(of name: String) -> Int ו-report() -> String. הפעולה Add מקבלת רק כמויות חיוביות. הפעולה Take מקבלת רק כמויות חיוביות שאינן עולות על המלאי הנוכחי. דחיות אינן משנות את המצב; הכמויות של פריטים לא מוכרים הן אפס. פעולות Take מוצלחות משאירות רשומות עם מלאי אפס. הדוח מציג את כל השמות השמורים בסדר עולה, בתבנית name:quantity ומופרדים ברווחים. הקלט מכיל 0 עד 40 שלשות פקודות: add name count או take name count. השמות הם מילים באותיות ASCII קטנות, באורך של עד 10 אותיות, והכמויות הן בטווח ‎-10 עד 100. הפלט הוא מספר הפקודות שהצליחו, ואחריו רווח והדוח רק אם אינו ריק.

ממש את ממשקי ה-API הנדרשים ואת solve(_ input: String) -> String. החזר את טקסט הפלט ללא ירידת שורה בסוף; אל תדפיס בקוד שניתן לעריכה. מנהל ההתקן הנעול בודק בנפרד את ממשקי ה-API עם קלטים תקינים נוספים, ואז מדפיס את הטקסט המוחזר עם ירידת שורה אחת בדיוק. כל הפעולות המספריות נשארות בגבולות Int.

אל Inventory ב-Go ניגשים דרך מצביע, והוא מחזיק מפה שהמפתחות שלה ממוינים במפורש לצורך יצירת הדוח. העתקה של ערך מפה ב-Go עדיין תשתף את הרשומות שמתחתיו. שמור על ממשק ה-API הנדרש של טיפוס הפניה ב-Swift ועל כל המצב לאחר פקודות שנדחו.

תוכנית הייחוס המלאה ב-Go. קמפל את קובצי package main האלה יחד; main.go מכיל את פונקציית main היחידה. המימוש שלם במכוון עבור ההעברה הסופית הזו.

inventory.go

package main
import ("sort"; "strconv"; "strings")
type Inventory struct { stock map[string]int }
func NewInventory() *Inventory { return &Inventory{stock: make(map[string]int)} }
func (inventory *Inventory) Quantity(name string) int { return inventory.stock[name] }
func (inventory *Inventory) Add(name string, count int) bool {
    if count <= 0 { return false }
    inventory.stock[name] = inventory.Quantity(name) + count
    return true
}
func (inventory *Inventory) Take(name string, count int) bool {
    available := inventory.Quantity(name)
    if count <= 0 || count > available { return false }
    inventory.stock[name] = available - count
    return true
}
func (inventory *Inventory) Report() string {
    names := make([]string, 0, len(inventory.stock))
    for name := range inventory.stock { names = append(names, name) }
    sort.Strings(names)
    rows := make([]string, 0, len(names))
    for _, name := range names { rows = append(rows, name+":"+strconv.Itoa(inventory.stock[name])) }
    return strings.Join(rows, " ")
}

main.go

package main
import ("bufio"; "fmt"; "os")
func main() {
    input := bufio.NewReader(os.Stdin)
    inventory := NewInventory()
    accepted := 0
    for {
        var command, name string
        var count int
        if _, err := fmt.Fscan(input, &command, &name, &count); err != nil { break }
        var ok bool
        if command == "add" { ok = inventory.Add(name, count) } else { ok = inventory.Take(name, count) }
        if ok { accepted++ }
    }
    report := inventory.Report()
    fmt.Print(accepted)
    if report != "" { fmt.Print(" ", report) }
    fmt.Println()
}

ממש את ממשקי ה-API של Swift בקבצים Inventory.swift, Functions.swift. השאר את מנהל ההתקן שסופק ב-main.swift.

נסו בעצמכם

import Foundation
func apiChecks(_ input: String) -> Bool {
let x = Inventory(); guard x.quantity(of: "missing") == 0 && !x.take("missing", count: 1) && x.report().isEmpty else { return false }; guard x.add("oak", count: 4) && !x.take("oak", count: 5) && !x.add("oak", count: 0) && x.quantity(of: "oak") == 4 else { return false }; return x.take("oak", count: 4) && x.report() == "oak:0" && !x.take("oak", count: -1) && Inventory().report().isEmpty
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// תחילת בדיקות ה-API הציבורי
let apiOK = apiChecks(input)
// סיום בדיקות ה-API הציבורי
if apiOK { print(solve(input)) } else { print("API mismatch") }

כל השיעורים ביחידה Swift למפתחי Go

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