Menu
CoddyTech

最终挑战:原子转账

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

challenge icon

挑战

简单

实现 Ledger,包含内部 int 类型的余额、Balance() int 和 Transfer(from,to *Ledger,n int) bool。遇到账户为 nil、金额为负数或资金不足时,拒绝转账,且不更改任一账户。否则,扣减一次并增加一次;如果余额足够,自转账会成功且余额不变。输入初始余额 a、b(非负),然后输入 n;所有数值都不超过一百万。

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

将代码写在 ledger.go 和 exercise.go 中。main.go 包含提供的输入/输出代码,不能编辑。保持为单一的扁平 package main;不要添加第二个 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 在线编译器