Menu
CoddyTech

Finale: porta un registro

Lezione 47 di 48 del corso Dart per sviluppatori Go di Coddy.

challenge icon

Sfida

Facile

Adatta il programma di riferimento. Implementa Ledger() con bool change(String name,int delta), int? get(String name) e List<String> report(). I nomi mancanti partono da zero quando vengono modificati; rifiuta un saldo risultante negativo senza apportare modifiche. Le modifiche riuscite pari a zero creano voci. Il report include solo i saldi positivi, ordinati per nome nel formato name=value. Le righe di input sono add name delta, get name oppure report, con nomi ASCII e interi con segno le cui somme rientrano in un milione. Ogni add restituisce testo booleano minuscolo; get restituisce il valore oppure missing; report restituisce voci separate da virgole oppure empty. Se non ci sono comandi, restituisce empty. Mantieni le API pubbliche utilizzabili in modo indipendente.

Non stampare dai file modificabili. Il file fornito exercise.dart analizza l'input e restituisce l'output; il driver bloccato verifica in modo indipendente le API pubbliche e stampa il risultato seguito da una sola nuova riga.

Il tuo codice va inserito in Ledger.dart, exercise.dart. main.dart contiene il codice fornito per input/output e non può essere modificato.

Programma di riferimento completo in Go:

package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
	"strings"
)

type Ledger struct{ balances map[string]int }

func newLedger() *Ledger { return &Ledger{balances: map[string]int{}} }

func (l *Ledger) change(name string, delta int) bool {
	value := l.balances[name] + delta
	if value < 0 {
		return false
	}
	l.balances[name] = value
	return true
}

func (l *Ledger) get(name string) (int, bool) {
	value, ok := l.balances[name]
	return value, ok
}

func (l *Ledger) report() []string {
	names := make([]string, 0, len(l.balances))
	for name, value := range l.balances {
		if value > 0 {
			names = append(names, name)
		}
	}
	sort.Strings(names)
	out := make([]string, len(names))
	for i, name := range names {
		out[i] = name + "=" + strconv.Itoa(l.balances[name])
	}
	return out
}

func main() {
	in := bufio.NewScanner(os.Stdin)
	ledger := newLedger()
	var out []string
	for in.Scan() {
		a := strings.Fields(in.Text())
		if len(a) == 0 {
			continue
		}
		switch a[0] {
		case "add":
			delta, _ := strconv.Atoi(a[2])
			out = append(out, strconv.FormatBool(ledger.change(a[1], delta)))
		case "get":
			if n, ok := ledger.get(a[1]); ok {
				out = append(out, strconv.Itoa(n))
			} else {
				out = append(out, "missing")
			}
		default:
			if r := ledger.report(); len(r) == 0 {
				out = append(out, "empty")
			} else {
				out = append(out, strings.Join(r, ","))
			}
		}
	}
	if len(out) == 0 {
		fmt.Println("empty")
	} else {
		fmt.Println(strings.Join(out, "\n"))
	}
}

Provalo tu

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

Tutte le lezioni di Dart per sviluppatori Go

Esercitati da solo: Compilatore Dart online