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 关注
- 66 浏览
添加回答
举报