最终挑战:库存核对
Coddy 面向 PHP 开发者的 Go 课程的第 47 课,共 48 课。
挑战
简单将源参考程序改写为 Go。两行输入分别提供以逗号分隔的名称和数量相同的整数调整值。按名称汇总,省略总数为零的项,并按字节顺序对键排序。返回 stock:,后面跟着以逗号分隔的 name=quantity 条目。输入为空时返回 stock:。名称由非空 ASCII 字母组成;总数的绝对值最多为 100 万。不要修改输入。
实现声明的 API;返回结果,不要打印。驱动程序会检查所需的 API,并保留调用方的输入。集合类型的标准输出使用 Go 的方括号格式,而不是 JSON。
将代码写入 exercise.go。main.go 包含提供的输入/输出代码,不能编辑。保持单一的扁平 package main;不要添加第二个 main。
PHP 参考程序
<?php
function inventory(array $names,array $changes):string {
$totals=[];
foreach($names as $i=>$name)$totals[$name]=($totals[$name]??0)+$changes[$i];
ksort($totals,SORT_STRING);
$rows=[];
foreach($totals as $name=>$quantity)if($quantity!==0)$rows[]=$name."=".$quantity;
return "stock:".implode(",",$rows);
}
echo 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)
}
面向 PHP 开发者的 Go中的所有课
自己练习: Go 在线编译器