Menu
CoddyTech

Final: Transferencia de cuenta

Lección 48 de 48 del curso GDScript para desarrolladores de C de Coddy.

challenge icon

Desafío

Fácil

Implementa FundsAccount(initial:int) con balance; FundsTransfer.move(source:FundsAccount,target:FundsAccount,n:int)->bool estático. Rechaza cuentas null, cantidades negativas o fondos insuficientes en la cuenta de origen sin modificar nada. De lo contrario, realiza la transferencia una vez. Una transferencia a la misma cuenta tiene éxito sin cambios netos si el saldo es suficiente. Solve toma [a,b,n] y devuelve success:a:b. Los saldos iniciales son no negativos.

La entrada es un array JSON en stdin. El main bloqueado lo analiza, llama a las API públicas e imprime result= seguido del texto devuelto y un salto de línea. Ninguna función auxiliar debe imprimir. Antes de probar la entrada, sondeadores fijos independientes verifican el comportamiento requerido de la API; no exigen un estilo de implementación concreto.

Referencia completa en C. Guarda estos archivos juntos y compila main.c con un compilador de C17. Los encabezados proporcionan la API auxiliar; main lee el mismo array JSON e imprime el mismo protocolo de resultado. No se requiere ninguna biblioteca externa.

Archivo 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

Archivo 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

Archivo 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;
}

Tu código va en funds_account.gd, funds_transfer.gd, exercise.gd. main.gd contiene el código de entrada/salida proporcionado y no se puede editar. Mantén cada tipo class_name en el archivo con su nombre.

Pruébalo tú mismo

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 las lecciones de GDScript para desarrolladores de C

Practica por tu cuenta: Compilador de GDScript online