1 回答

TA貢獻1829條經驗 獲得超4個贊
正如評論所指出的,問題在于當前Recipe的更新機制。字符串按值傳遞。
這是正確的代碼
package main
import (
"bufio"
"fmt"
"os"
"regexp"
)
func main() {
nutriments := map[string][]string{
"flour":{"sugars"},
"egg":{"protein", "fat"},
"tomato":{"water", "viamins"},
"cheese":{"calcium", "protein"},
"apple":{"sugars", "fiber", "vitamin"} }
total := make(map[string]map[string]bool)
f := bufio.NewScanner(os.Stdin)
currentRecipe := ""
for f.Scan() {
currentRecipe = Line(f.Text(), currentRecipe, nutriments, total)
}
fmt.Println(total)
}
func Line (line, currentRecipe string, nut map[string][]string, tot map[string]map[string]bool) string {
if foundrec, _ := regexp.MatchString("^# [[:graph:]]+", line); foundrec { // Begin recipe
currentRecipe = line[2:]
fmt.Println("---------", currentRecipe) // update current
tot[currentRecipe] = make(map[string]bool) // prepare set
}
if foundnut, _ := regexp.MatchString("^- [[:graph:]]+", line); foundnut { // Begin ingredients list
nutri := line[2:]
tot[currentRecipe][nutri] = true
}
return currentRecipe
}
- 1 回答
- 0 關注
- 81 瀏覽
添加回答
舉報