最終課題:在庫の照合
Coddyの「C++開発者のためのGo」コースのレッスン 47/48。
チャレンジ
簡単ソースの参照仕様をGoに移植してください。2行の入力には、カンマ区切りの名前と、それと同じ個数の整数の調整値が含まれます。名前ごとに集計し、合計が0のものを除外して、キーをバイト単位でソートしてください。stock:の後に、カンマ区切りの名前=数量の項目を続けて返してください。入力が空の場合はstock:を返します。名前は空でないASCII文字のみで構成されます。合計値の絶対値は最大で100万です。入力を変更しないでください。
宣言されたAPIを実装し、結果を出力せずに返してください。ドライバーは必要なAPIを確認し、呼び出し元の入力を保持します。コレクションの標準出力ではJSONではなく、Goの角括弧形式を使用します。
コードはexercise.goに記述してください。main.goには提供された入出力コードがあり、編集できません。単一のフラットなpackage mainを保ち、2つ目の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オンラインコンパイラ