Menu
CoddyTech

Finale: trasferimento atomico

Lezione 48 di 48 del corso Go per sviluppatori PHP di Coddy.

challenge icon

Sfida

Facile

Implementa Ledger con un saldo interno int, Balance() int e Transfer(from,to *Ledger,n int) bool. Rifiuta gli account nil, gli importi negativi e i fondi insufficienti senza modificare nessuno dei due account. Altrimenti sottrai una volta e aggiungi una volta; il trasferimento a sé stessi riesce senza modifiche nette se l'importo è sostenibile. Inserisci i saldi iniziali a,b (non negativi) e poi n; tutti i valori assoluti sono al massimo un milione.

Implementa le API dichiarate; restituisci i risultati senza stamparli. Il driver verifica le API richieste e preserva l'input del chiamante. L'output stdout delle collezioni usa la formattazione con parentesi quadre di Go, non JSON.

Il tuo codice va in ledger.go, exercise.go. main.go contiene il codice fornito per input/output e non può essere modificato. Mantieni un unico package main senza annidamenti; non aggiungere un secondo main.

Programma di riferimento in 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);

Output di riferimento:

true:6:6

Provalo tu

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)
}

Tutte le lezioni di Go per sviluppatori PHP

Esercitati da solo: Compilatore Go online