Menu
CoddyTech

最终挑战:原子转账

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

challenge icon

挑战

简单

实现 Ledger,包含内部余额 int、Balance() int 和 Transfer(from,to *Ledger,n int) bool。遇到账户为 nil、金额为负数或余额不足时,拒绝转账,且不更改任一账户。否则,扣除一次并增加一次;如果金额可承担,自转账应成功且余额不变。输入起始余额 a、b(均为非负数),然后输入 n;所有数值的绝对值都不超过 1,000,000。

实现声明的 API;返回结果,不要打印。驱动程序会检查必需的 API,并保留调用方的输入。集合类型的 stdout 使用 Go 的方括号格式,而不是 JSON。

你的代码写在 ledger.go、exercise.go 中。main.go 包含提供的输入/输出代码,不能修改。保持一个扁平的 package main;不要添加第二个 main。

PHP 参考程序

<?php
class Ledger {
    private int $amount;
    function __construct(int $opening){$this->amount=$opening;}
    function balance():int{return $this->amount;}
    static function transfer(?Ledger $from,?Ledger $to,int $n):bool {
        if($from===null || $to===null || $n<0 || $n>$from->amount)return false;
        $from->amount-=$n;$to->amount+=$n;return true;
    }
}
function check(bool $ok):void {if(!$ok)throw new RuntimeException("reference invariant");}
$a=new Ledger(10);$b=new Ledger(2);$ok=Ledger::transfer($a,$b,4);
echo ($ok ? "true":"false"),":",$a->balance(),":",$b->balance(),"\n";
check(Ledger::transfer($a,$a,3));check(Ledger::transfer($a,$b,0));
check(!Ledger::transfer($a,$b,-1));check(!Ledger::transfer($a,$b,7));
check(!Ledger::transfer(null,$b,1));check(!Ledger::transfer($a,null,1));
check($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)
}

面向 PHP 开发者的 Go中的所有课

自己练习: Go 在线编译器