终极:股票账本
Coddy 面向 Go 开发者的 R 语言 课程的第 47 课,共 48 课。
挑战
简单实现 summarize(rows)。每行为一个小写 ASCII 项目名称和一个有符号整数金额,中间用一个空格分隔。按名称累加金额;仅保留正数总额;按字典序对名称排序;返回以换行符分隔的 name:total 条目,若无则返回 `"empty"`。空输入是有效的。
保持已声明的公共 API。可见的锁定驱动代码会直接对其进行检查,并打印 solve(lines)。输入均满足说明的契约;所有算术运算均较小且有限。
你的代码放在 Functions.R 和 Exercise.R 中。main.R 按顺序加载依赖项并包含提供的输入/输出代码;它不可编辑。
将这个完整的 Go 参考代码移植到 R 公共 API 中。它实现了相同的有效输入契约。
package main
import (
"bufio"
"fmt"
"io"
"os"
"sort"
"strconv"
"strings"
)
func summarize(rows []string) string {
totals:=map[string]int64{}
for _,row:=range rows {
parts:=strings.SplitN(row," ",2)
amount,err:=strconv.ParseInt(parts[1],10,64)
if err!=nil {panic(err)}
totals[parts[0]]+=amount
}
names:=[]string{}
for name,total:=range totals {if total>0 {names=append(names,name)}}
sort.Strings(names)
lines:=make([]string,0,len(names))
for _,name:=range names {
lines=append(lines,name+":"+strconv.FormatInt(totals[name],10))
}
if len(lines)==0 {return "empty"}
return strings.Join(lines,"\n")
}
func main() {
reader:=bufio.NewReader(os.Stdin)
rows:=[]string{}
for {
line,err:=reader.ReadString('\n')
if len(line)>0 {
rows=append(rows,strings.TrimSuffix(strings.TrimSuffix(line,"\n"),"\r"))
}
if err==io.EOF {break}
if err!=nil {panic(err)}
}
fmt.Println(summarize(rows))
}
亲手试试
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="")
面向 Go 开发者的 R 语言中的所有课
自己练习: R 在线编译器