最终挑战:原子转账
Coddy 面向 C++ 开发者的 Go 课程的第 48 课,共 48 课。
挑战
简单实现 Ledger,包含内部 balance 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 <cassert>
#include <iostream>
class Ledger {
int amount;
public:
explicit Ledger(int opening):amount(opening){}
int balance() const{return amount;}
static bool transfer(Ledger* from,Ledger* to,int n) {
if(from==nullptr || to==nullptr || n<0 || n>from->amount)return false;
from->amount-=n;to->amount+=n;return true;
}
};
int main(){
Ledger a(10),b(2);bool ok=Ledger::transfer(&a,&b,4);
std::cout<<std::boolalpha<<ok<<':'<<a.balance()<<':'<<b.balance()<<'\n';
assert(Ledger::transfer(&a,&a,3) && a.balance()==6);
assert(Ledger::transfer(&a,&b,0));
assert(!Ledger::transfer(&a,&b,-1) && !Ledger::transfer(&a,&b,7));
assert(!Ledger::transfer(nullptr,&b,1) && !Ledger::transfer(&a,nullptr,1));
assert(a.balance()==6 && b.balance()==6);
}参考输出:
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 在线编译器