Menu
CoddyTech

최종: 원장 포팅

Coddy의 Go 개발자를 위한 Dart 코스 레슨. 48개 중 47번째.

challenge icon

챌린지

쉬움

원본 참조 프로그램을 포팅하세요. Ledger()에 bool change(String name,int delta), int? get(String name), List<String> report()를 구현하세요. 변경 시 없는 이름은 0에서 시작하고, 변경 결과 잔액이 음수이면 상태를 바꾸지 않고 거부하세요. 값이 0인 변경도 성공하면 항목을 생성합니다. 양수 잔액만 이름순으로 정렬하여 name=value 형식으로 보고하세요. 입력 행은 add name delta, get name 또는 report이며, 이름은 ASCII 문자이고 부호가 있는 정수의 합은 1백만 이하여야 합니다. 각 add는 소문자 불리언 텍스트를 출력하고, get은 값 또는 missing을 출력하며, report는 쉼표로 구분된 항목 또는 empty를 출력합니다. 명령이 없으면 empty를 출력합니다. 공개 API를 독립적으로 사용할 수 있도록 유지하세요.

편집 가능한 파일에서 출력하지 마세요. 제공된 exercise.dart가 입력을 분석하고 출력을 반환합니다. 잠긴 드라이버는 공개 API를 독립적으로 검사하고 결과를 줄바꿈 문자 하나와 함께 출력합니다.

코드는 Ledger.dart, exercise.dart에 작성하세요. main.dart에는 제공된 입력/출력 코드가 있으며 편집할 수 없습니다.

완성된 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"))
	}
}

직접 해보기

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

Go 개발자를 위한 Dart의 모든 레슨

직접 연습해 보세요: 온라인 Dart 컴파일러