Menu
CoddyTech

Final: Adaptar un libro mayor

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

challenge icon

Desafío

Fácil

Adapta el programa de referencia de origen. Implementa Ledger() con bool change(String name,int delta), int? get(String name) y List<String> report(). Los nombres que no existan empiezan en cero al modificarlos; rechaza cualquier cambio que dé como resultado un saldo negativo, sin modificarlo. Los cambios exitosos de cero crean entradas. Informa solo de los saldos positivos, ordenados por nombre, como name=value. Las líneas de entrada son add name delta, get name o report, con nombres ASCII y enteros con signo cuyas sumas no superan un millón. Cada operación add emite texto booleano en minúsculas; get emite el valor o missing; report emite entradas separadas por comas o empty. Si no hay comandos, se emite empty. Mantén las API públicas utilizables de forma independiente.

No imprimas desde los archivos editables. El archivo exercise.dart proporcionado analiza la entrada y devuelve la salida; el controlador bloqueado prueba las API públicas de forma independiente e imprime el resultado con un salto de línea.

Tu código va en Ledger.dart y exercise.dart. main.dart contiene el código proporcionado para la entrada y la salida y no se puede editar.

Programa de referencia completo en C:

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct entry {
    char *name;
    int balance;
};

struct ledger {
    struct entry *items; /* kept sorted by name */
    size_t len, cap;
};

static struct entry *ledger_find(const struct ledger *l, const char *name, size_t *pos) {
    size_t i = 0;
    while (i < l->len && strcmp(l->items[i].name, name) < 0) i++;
    *pos = i;
    return i < l->len && strcmp(l->items[i].name, name) == 0 ? &l->items[i] : NULL;
}

static bool ledger_change(struct ledger *l, const char *name, int delta) {
    size_t pos;
    struct entry *e = ledger_find(l, name, &pos);
    int value = (e ? e->balance : 0) + delta;
    if (value < 0) return false;
    if (e) {
        e->balance = value;
        return true;
    }
    if (l->len == l->cap) {
        l->cap = l->cap ? l->cap * 2 : 8;
        l->items = realloc(l->items, l->cap * sizeof *l->items);
        if (!l->items) exit(1);
    }
    memmove(&l->items[pos + 1], &l->items[pos], (l->len - pos) * sizeof *l->items);
    size_t n = strlen(name) + 1;
    l->items[pos] = (struct entry){malloc(n), value};
    memcpy(l->items[pos].name, name, n);
    l->len++;
    return true;
}

static const int *ledger_get(const struct ledger *l, const char *name) {
    size_t pos;
    const struct entry *e = ledger_find(l, name, &pos);
    return e ? &e->balance : NULL;
}

static void ledger_report(const struct ledger *l) {
    bool any = false;
    for (size_t i = 0; i < l->len; i++) {
        if (l->items[i].balance <= 0) continue;
        printf("%s%s=%d", any ? "," : "", l->items[i].name, l->items[i].balance);
        any = true;
    }
    printf("%s\n", any ? "" : "empty");
}

int main(void) {
    struct ledger ledger = {NULL, 0, 0};
    char line[1024];
    int lines = 0;
    while (fgets(line, sizeof line, stdin)) {
        const char *cmd = strtok(line, " \t\r\n");
        if (!cmd) continue;
        const char *name = strtok(NULL, " \t\r\n");
        lines++;
        if (strcmp(cmd, "add") == 0) {
            printf("%s\n", ledger_change(&ledger, name, atoi(strtok(NULL, " \t\r\n"))) ? "true" : "false");
        } else if (strcmp(cmd, "get") == 0) {
            const int *n = ledger_get(&ledger, name);
            if (n) printf("%d\n", *n);
            else printf("missing\n");
        } else {
            ledger_report(&ledger);
        }
    }
    if (lines == 0) printf("empty\n");
    for (size_t i = 0; i < ledger.len; i++) free(ledger.items[i].name);
    free(ledger.items);
    return 0;
}

Pruébalo tú mismo

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

Todas las lecciones de Dart para desarrolladores de C

Practica por tu cuenta: Compilador de Dart online