Menu
CoddyTech

Final: Port a Ledger

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

challenge icon

Challenge

Easy

Port the source reference program. Implement Ledger() with bool change(String name,int delta), int? get(String name), and List<String> report(). Missing names start at zero for changes; reject a negative resulting balance without mutation. Successful zero changes create entries. Report only positive balances, sorted by name as name=value. Input lines are add name delta, get name, or report, with ASCII names and signed integers whose sums fit one million. Each add emits lowercase Boolean text; get emits value or missing; report emits comma-separated entries or empty. No commands yields empty. Keep the public APIs usable independently.

Do not print from editable files. The supplied exercise.dart parses input and returns output; the locked driver independently probes the public APIs and prints the result with one newline.

Your code goes in Ledger.dart, exercise.dart. main.dart holds the supplied input/output code and cannot be edited.

Complete GDScript reference program:

extends Node
class Ledger:
    var balances: Dictionary = {}
    func change(key: String, delta: int) -> bool:
        var value: int = balances.get(key, 0) + delta
        if value < 0:
            return false
        balances[key] = value
        return true
    func balance(key: String):
        return balances.get(key)
    func report() -> PackedStringArray:
        var keys = balances.keys()
        keys.sort()
        var result := PackedStringArray()
        for key in keys:
            if balances[key] > 0:
                result.append("%s=%s" % [key, balances[key]])
        return result
func _ready() -> void:
    var input := PackedByteArray()
    while true:
        var chunk = OS.read_buffer_from_stdin(4096)
        if chunk.is_empty():
            break
        input.append_array(chunk)
    var ledger = Ledger.new()
    var output := PackedStringArray()
    var words = RegEx.new()
    words.compile("\\S+")
    for line in input.get_string_from_utf8().split("\n"):
        var parts: Array[String] = []
        for item in words.search_all(line):
            parts.append(item.get_string())
        if parts.is_empty():
            continue
        if parts[0] == "add":
            output.append(str(ledger.change(parts[1], parts[2].to_int())))
        elif parts[0] == "get":
            var value = ledger.balance(parts[1])
            output.append("missing" if value == null else str(value))
        else:
            var rows = ledger.report()
            output.append("empty" if rows.is_empty() else ",".join(rows))
    print("empty" if output.is_empty() else "\n".join(output))

Try it yourself

import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Ledger.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
final l=Ledger();check(l.change('a',4)&&!l.change('a',-5)&&l.get('a')==4);check(l.change('z',0)&&l.get('z')==0&&l.get('missing')==null);check(l.report().join(',')=='a=4');
stdout.writeln(solve(input));
}

All lessons in Dart for GDScript Developers

Practice on your own: Online Dart compiler