最終課題:原子的な振替
Coddyの「C開発者のためのGo」コースのレッスン 48/48。
チャレンジ
簡単内部残高として int を持ち、Balance() int と Transfer(from,to *Ledger,n int) bool を備えた Ledger を実装してください。nil アカウント、負の金額、残高不足の場合は、どちらのアカウントも変更せずに拒否してください。それ以外の場合は、一度減算して一度加算してください。自己送金は、支払い可能な金額であれば成功し、残高は変わりません。入力は開始残高 a,b(非負)、続いて n です。すべての数値の絶対値は最大で 100 万です。
宣言された API を実装し、結果を返してください。出力はしないでください。ドライバーは必要な API を確認し、呼び出し元の入力を保持します。コレクションの標準出力には JSON ではなく、Go の角括弧形式が使われます。
コードは ledger.go と exercise.go に記述してください。main.go には用意された入力/出力コードが含まれており、編集できません。単一のフラットな package main を維持し、2つ目の main を追加しないでください。
C の参照プログラム
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
struct Ledger { int balance; };
static bool transfer(struct Ledger *from,struct Ledger *to,int amount) {
if(from==NULL || to==NULL || amount<0 || amount>from->balance)return false;
from->balance-=amount;
to->balance+=amount;
return true;
}
int main(void) {
struct Ledger a={10},b={2};
bool ok=transfer(&a,&b,4);
printf("%s:%d:%d\n",ok ? "true":"false",a.balance,b.balance);
assert(transfer(&a,&a,3) && a.balance==6);
assert(transfer(&a,&b,0) && a.balance==6 && b.balance==6);
assert(!transfer(&a,&b,-1) && !transfer(&a,&b,7));
assert(!transfer(NULL,&b,1) && !transfer(&a,NULL,1));
assert(a.balance==6 && b.balance==6);
return 0;
}参照出力:
true:6:6自分で試してみよう
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:=I(0); before0:=fmt.Sprint(a0)
a1:=I(1); before1:=fmt.Sprint(a1)
a2:=I(2); before2:=fmt.Sprint(a2)
a:=Ledger{9};b:=Ledger{1};must(Transfer(&a,&b,4)&&a.Balance()==5&&b.Balance()==5,"transfer API");must(!Transfer(&a,&b,6)&&a.Balance()==5&&b.Balance()==5,"atomic failure");must(Transfer(&a,&a,2)&&a.Balance()==5,"self transfer");must(!Transfer(nil,&b,0),"nil transfer");
result:=Solve(a0,a1,a2)
must(fmt.Sprint(a0)==before0,"input mutation")
must(fmt.Sprint(a1)==before1,"input mutation")
must(fmt.Sprint(a2)==before2,"input mutation")
fmt.Println(result)
}
C開発者のためのGoのすべてのレッスン
自分で練習してみよう: Goオンラインコンパイラ