最終課題:口座の移管
Coddyの「C開発者向けGDScript」コースのレッスン 48/48。
チャレンジ
簡単balanceを持つFundsAccount(initial:int)を実装してください。static FundsTransfer.move(source:FundsAccount,target:FundsAccount,n:int)->boolも実装してください。nullのアカウント、負の金額、またはsourceの残高不足の場合は、状態を変更せずに拒否してください。それ以外の場合は一度だけ送金してください。自己送金は、金額をまかなえる場合に成功し、残高は変わりません。Solveは[a,b,n]を受け取り、success:a:bを返します。初期残高は非負です。
入力は標準入力のJSON配列1つです。ロックされたmainはこれを解析し、公開APIを呼び出して、result=に返されたテキストを続けたものと改行を出力します。ヘルパー関数から出力してはいけません。入力ケースの前に、独立した固定プローブで必須のAPI動作を検証します。実装スタイルは検査しません。
Cの完全な参照実装です。これらのファイルを同じ場所に保存し、C17コンパイラでmain.cをコンパイルしてください。ヘッダーにはヘルパーAPIが定義されています。mainは同じJSON配列を読み取り、同じ結果プロトコルで出力します。外部ライブラリは不要です。
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
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
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;
}
コードはfunds_account.gd、funds_transfer.gd、exercise.gdに記述してください。main.gdには提供された入出力コードが含まれており、編集できません。各class_name型は、対応する名前のファイルに記述してください。
自分で試してみよう
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))
C開発者向けGDScriptのすべてのレッスン
自分で練習してみよう: GDScriptオンラインコンパイラ