Menu
CoddyTech

最終課題:在庫の照合

Coddyの「C開発者のためのGo」コースのレッスン 47/48。

challenge icon

チャレンジ

簡単

ソースの参照仕様をGoに移植します。2行の入力には、カンマ区切りの名前と、それと同数の整数の調整値が含まれます。名前ごとに集計し、合計が0のものを除外して、キーをバイト順に並べ替えます。stock:に続けて、カンマ区切りのname=quantity形式の項目を返します。入力が空の場合はstock:を返します。名前は空ではないASCII文字です。合計の絶対値は最大で100万です。入力を変更してはいけません。

宣言されたAPIを実装し、結果を出力せずに返してください。ドライバーは必要なAPIを確認し、呼び出し元の入力を保持します。コレクションの標準出力には、JSONではなくGoの角括弧形式が使われます。

コードはexercise.goに記述してください。main.goには提供された入出力コードがあり、編集できません。単一のフラットなpackage mainを維持してください。2つ目のmainを追加してはいけません。

Cの参照プログラム

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Entry { const char *name; int total; };
static int compare(const void *left,const void *right) {
    const struct Entry *a=left,*b=right;
    return strcmp(a->name,b->name);
}
/* Caller owns names and changes; this function does not modify them. */
static void inventory(const char *const names[],const int changes[],size_t count) {
    struct Entry *entries=calloc(count ? count : 1,sizeof(*entries));
    assert(entries != NULL);
    size_t used=0;
    for(size_t i=0;i<count;i++) {
        size_t j=0;
        while(j<used && strcmp(entries[j].name,names[i])!=0)j++;
        if(j==used){entries[used].name=names[i];used++;}
        entries[j].total+=changes[i];
    }
    qsort(entries,used,sizeof(*entries),compare);
    printf("stock:");
    int first=1;
    for(size_t i=0;i<used;i++)if(entries[i].total!=0) {
        printf("%s%s=%d",first ? "":",",entries[i].name,entries[i].total);
        first=0;
    }
    puts("");
    free(entries);
}
int main(void) {
    const char *names[]={"pen","book","pen"};int changes[]={2,1,-1};
    inventory(names,changes,3);
    return 0;
}

参照出力:

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オンラインコンパイラ