Menu
CoddyTech

Final: transferência de conta

Lição 48 de 48 do curso GDScript para desenvolvedores C da Coddy.

challenge icon

Desafio

Fácil

Implemente FundsAccount(initial:int) com balance; static FundsTransfer.move(source:FundsAccount,target:FundsAccount,n:int)->bool. Rejeite contas null, valores negativos ou fundos insuficientes na origem sem fazer alterações. Caso contrário, faça a transferência uma vez. A transferência para a própria conta é bem-sucedida sem alteração líquida quando há fundos suficientes. Solve recebe [a,b,n] e retorna success:a:b. Os saldos iniciais são não negativos.

A entrada é um único array JSON em stdin. O main bloqueado faz o parse, chama as APIs públicas e imprime result= seguido do texto retornado e de uma nova linha. Nenhuma função auxiliar deve imprimir. Testes independentes e fixos verificam o comportamento exigido da API antes do caso de entrada; eles não impõem um estilo de implementação.

Implementação C de referência completa. Salve esses arquivos juntos e compile main.c com um compilador C17. Os cabeçalhos fornecem a API auxiliar; main lê o mesmo array JSON e imprime o mesmo protocolo de resultado. Nenhuma biblioteca externa é necessária.

Arquivo C account.h:

#ifndef ACCOUNT_H
#define ACCOUNT_H
#include <stdint.h>
struct Account { int64_t balance; };
static inline struct Account account_make(int64_t initial) {
    return (struct Account){initial};
}
#endif

Arquivo C transfers.h:

#ifndef TRANSFERS_H
#define TRANSFERS_H
#include <stdbool.h>
#include "account.h"
static inline bool transfer_move(struct Account *source,
                                 struct Account *target, int64_t amount) {
    if (!source || !target || amount<0 || amount>source->balance) return false;
    if (source==target) return true;
    /* Match the reference's unchecked 64-bit arithmetic without C overflow. */
    uint64_t sum=(uint64_t)target->balance+(uint64_t)amount;
    source->balance-=amount;
    target->balance=sum <= INT64_MAX ? (int64_t)sum : -1-(int64_t)(UINT64_MAX-sum);
    return true;
}
#endif

Arquivo C main.c:

#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "transfers.h"
int main(int argc, char **argv) {
    if (argc>1 && strcmp(argv[1],"--probe")==0) {
        struct Account a=account_make(6);
        if (transfer_move(NULL,&a,0) || transfer_move(&a,NULL,0) ||
            !transfer_move(&a,&a,4) || a.balance!=6 ||
            transfer_move(&a,&a,7) || a.balance!=6) return 1;
        puts("contract-ok"); return 0;
    }
    int64_t a,b,n;
    if (scanf(" [ %" SCNd64 " , %" SCNd64 " , %" SCNd64 " ]",&a,&b,&n)!=3) return 1;
    struct Account source=account_make(a),target=account_make(b);
    bool moved=transfer_move(&source,&target,n);
    printf("result=%s:%" PRId64 ":%" PRId64 "\n",
           moved?"true":"false",source.balance,target.balance);
    return 0;
}

Seu código deve ser colocado em funds_account.gd, funds_transfer.gd, exercise.gd. main.gd contém o código fornecido de entrada/saída e não pode ser editado. Mantenha cada tipo class_name no arquivo com o mesmo nome.

Experimente você mesmo

extends Node

func contract_ok(data: Array) -> bool:
	var a: FundsAccount = FundsAccount.new(6)
	var b: FundsAccount = FundsAccount.new(2)
	if FundsTransfer.move(null,b,0) or FundsTransfer.move(a,null,0) or FundsTransfer.move(a,b,7) or FundsTransfer.move(a,b,-1): return false
	if a.balance != 6 or b.balance != 2: return false
	if not FundsTransfer.move(a,a,4) or a.balance != 6: return false
	if not FundsTransfer.move(a,b,3) or a.balance != 3 or b.balance != 5: return false
	return true

func _ready() -> void:
	var data: Array = JSON.parse_string(OS.read_string_from_stdin())
	if not contract_ok(data):
		print("API_CONTRACT_FAILED")
		return
	print("result=" + Exercise.solve(data))

Todas as lições de GDScript para desenvolvedores C

Pratique por conta própria: Compilador de GDScript online