Menu
CoddyTech

最终挑战:库存核对

Coddy 面向 C++ 开发者的 Go 课程的第 47 课,共 48 课。

challenge icon

挑战

简单

将源参考契约移植到 Go。两行输入分别提供以逗号分隔的名称和数量相同的整数调整值。按名称汇总,忽略总和为零的项,并按字节顺序对键排序。返回以 stock: 开头、后接以逗号分隔的 name=quantity 条目。输入为空时返回 stock:。名称为非空的 ASCII 字母;总量的绝对值最多为一百万。不要修改输入。

实现声明的 API;返回结果,不要打印。驱动程序会检查所需的 API,并保留调用方的输入。集合的标准输出采用 Go 的方括号格式,而不是 JSON。

将代码写入 exercise.go。main.go 包含提供的输入/输出代码,不能编辑。保持一个扁平的 package main,不要添加第二个 main。

C++ 参考程序

#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
std::string inventory(const std::vector<std::string>& names,const std::vector<int>& changes) {
    std::map<std::string,int> totals;
    for(std::size_t i=0;i<names.size();++i)totals[names[i]]+=changes[i];
    std::ostringstream out;out<<"stock:";bool first=true;
    for(const auto& item:totals)if(item.second!=0) {
        if(!first)out<<',';
        out<<item.first<<'='<<item.second;first=false;
    }
    return out.str();
}
int main(){std::cout<<inventory({"pen","book","pen"},{2,1,-1})<<'\n';}

参考输出:

stock:book=1,pen=1

亲手试试

package main
import ("fmt";"strings";"strconv";"bufio";"os")
var input []string
func L(i int)string{if i<len(input){return input[i]};return ""}
func I(i int)int{n,e:=strconv.Atoi(L(i));if e!=nil{panic(e)};return n}
func Ints(i int)[]int{out:=[]int{};if L(i)==""{return out};for _,s:=range strings.Split(L(i),","){n,e:=strconv.Atoi(s);if e!=nil{panic(e)};out=append(out,n)};return out}
func Words(i int)[]string{if L(i)==""{return []string{}};return strings.Split(L(i),",")}
func must(ok bool,message string){if !ok{panic("API: "+message)}}

func main(){
scanner:=bufio.NewScanner(os.Stdin);for scanner.Scan(){input=append(input,scanner.Text())};if scanner.Err()!=nil{panic(scanner.Err())}
a0:=Words(0); before0:=fmt.Sprint(a0)
a1:=Ints(1); before1:=fmt.Sprint(a1)

result:=Solve(a0,a1)
must(fmt.Sprint(a0)==before0,"input mutation")
must(fmt.Sprint(a1)==before1,"input mutation")
fmt.Println(result)
}

面向 C++ 开发者的 Go中的所有课

自己练习: Go 在线编译器