Menu
CoddyTech

Final: Account Transfer

Lesson 48 of 48 in Coddy's GDScript for Rust Developers course.

challenge icon

Challenge

Easy

Implement FundsAccount(initial:int) with balance; static FundsTransfer.move(source:FundsAccount,target:FundsAccount,n:int)->bool. Reject null accounts, negative amount or insufficient source funds without mutation. Otherwise transfer once. Self-transfer succeeds without net change when affordable. Solve takes [a,b,n] and returns success:a:b. Initial balances nonnegative.

Input is one JSON array on stdin. The locked main parses it, calls the public APIs and prints result= followed by the returned text and a newline. No helper should print. Independent fixed probes verify required API behavior before the input case; they do not enforce implementation style.

Your code goes in funds_account.gd, funds_transfer.gd, exercise.gd. main.gd holds the supplied input/output code and cannot be edited. Keep each class_name type in its named file.

Input bounds: initial balances are integers from 0 to 1000000, and the requested amount is an integer from -1000000 to 1000000. The public API also handles null accounts and self-transfer as described.

Complete Rust reference program. It reads the same JSON array from stdin and writes the same result line:

Rust file account.rs:

pub struct Account { pub balance:i64 }
impl Account { pub fn new(balance:i64)->Self { Self{balance} } }

Rust file transfer.rs:

use std::{rc::Rc,cell::RefCell};
use crate::account::Account;
pub fn move_funds(source:Option<&Rc<RefCell<Account>>>,target:Option<&Rc<RefCell<Account>>>,amount:i64)->bool {
    let (Some(source),Some(target))=(source,target) else { return false; };
    if amount<0 || amount>source.borrow().balance { return false; }
    source.borrow_mut().balance-=amount;
    target.borrow_mut().balance+=amount;
    true
}

Rust file main.rs:

mod account; mod transfer;
use std::{rc::Rc,cell::RefCell,io::{self,Read}};
fn main() {
    let probe=Rc::new(RefCell::new(account::Account::new(5)));
    assert!(transfer::move_funds(Some(&probe),Some(&probe),3));
    assert_eq!(probe.borrow().balance,5);
    assert!(!transfer::move_funds(None,Some(&probe),0));
    let mut input=String::new(); io::stdin().read_to_string(&mut input).expect("stdin");
    let inner=input.trim().strip_prefix('[').and_then(|s|s.strip_suffix(']')).expect("array");
    let values:Vec<i64>=inner.split(',').map(|s| {
        let value=s.trim().parse::<f64>().expect("number");
        assert!(value.is_finite() && value.fract()==0.0 && value.abs()<=1_000_000.0);
        value as i64
    }).collect();
    assert_eq!(values.len(),3);
    let source=Rc::new(RefCell::new(account::Account::new(values[0])));
    let target=Rc::new(RefCell::new(account::Account::new(values[1])));
    let success=transfer::move_funds(Some(&source),Some(&target),values[2]);
    println!("result={}:{}:{}",success,source.borrow().balance,target.borrow().balance);
}

Try it yourself

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

All lessons in GDScript for Rust Developers

Practice on your own: Online GDScript compiler