Finał: Portowanie ekwipunku
Lekcja 47 z 48 w kursie Ruby dla programistów GDScript w Coddy.
Wyzwanie
ŁatwyPrzenieś program referencyjny. Zapas początkowo wynosi zero; change(delta) akceptuje zmianę tylko wtedy, gdy jej wynikiem jest nieujemny zapas, i zwraca true albo false. quantity odczytuje stan zapasu. Inventory.change(code,delta) stosuje zmiany dla każdego kodu, tworząc kod tylko w przypadku powodzenia. report zwraca dodatnie ilości w kolejności alfabetycznej kodów jako pary code:quantity albo none. Dane wejściowe składają się z par kod delta, po jednej w każdym wierszu. Wynikiem jest jedna wartość logiczna dla każdej zmiany, a następnie raport. Umieść Stock i Inventory w osobnych plikach.
Zwróć tekst z solve(input) bez wypisywania go. Zablokowany sterownik wypisuje zwrócony tekst z jednym końcowym znakiem nowej linii i niezależnie sprawdza wymagane publiczne API.
Umieść swój kod w plikach exercise.rb, stock.rb, inventory.rb. Plik main.rb zawiera dostarczony kod wejścia/wyjścia i nie można go edytować.
Program referencyjny w GDScript. Odwzoruj jego działanie, używając wymaganych interfejsów API Ruby.
extends SceneTree
class Decimal:
static func normalize(text: String) -> String:
var negative = text.begins_with("-")
if text.begins_with("+") or negative:
text = text.substr(1)
var i = 0
while i < text.length() - 1 and text[i] == "0":
i += 1
text = text.substr(i)
return "-" + text if negative and text != "0" else text
static func compare_abs(a: String, b: String) -> int:
if a.length() != b.length():
return 1 if a.length() > b.length() else -1
return 0 if a == b else (1 if a > b else -1)
static func add_abs(a: String, b: String) -> String:
var i = a.length() - 1
var j = b.length() - 1
var carry = 0
var out = ""
while i >= 0 or j >= 0 or carry > 0:
var value = carry
if i >= 0:
value += a.unicode_at(i) - 48
if j >= 0:
value += b.unicode_at(j) - 48
out = str(value % 10) + out
carry = 1 if value >= 10 else 0
i -= 1
j -= 1
return out
static func subtract_abs(a: String, b: String) -> String:
var i = a.length() - 1
var j = b.length() - 1
var borrow = 0
var out = ""
while i >= 0:
var digit = a.unicode_at(i) - 48 - borrow
if j >= 0:
digit -= b.unicode_at(j) - 48
borrow = 1 if digit < 0 else 0
if digit < 0:
digit += 10
out = str(digit) + out
i -= 1
j -= 1
return normalize(out)
static func add(a: String, b: String) -> String:
a = normalize(a)
b = normalize(b)
var an = a.begins_with("-")
var bn = b.begins_with("-")
var av = a.substr(1) if an else a
var bv = b.substr(1) if bn else b
if an == bn:
var sum = add_abs(av, bv)
return "-" + sum if an and sum != "0" else sum
var order = compare_abs(av, bv)
if order == 0:
return "0"
var difference = subtract_abs(av, bv) if order > 0 else subtract_abs(bv, av)
var negative = an if order > 0 else bn
return "-" + difference if negative else difference
class Stock:
var quantity = "0"
func change(delta: String) -> bool:
var next = Decimal.add(quantity, delta)
if next.begins_with("-"):
return false
quantity = next
return true
class Inventory:
var items = {}
func change(code: String, delta: String) -> bool:
var stock = items.get(code, Stock.new())
if not stock.change(delta):
return false
items[code] = stock
return true
func report() -> String:
var codes = items.keys()
codes.sort()
var parts = PackedStringArray()
for code in codes:
if items[code].quantity != "0":
parts.append(code + ":" + items[code].quantity)
return "none" if parts.is_empty() else " ".join(parts)
func _init():
var inventory = Inventory.new()
var whitespace = RegEx.new()
whitespace.compile("\\s+")
while true:
var line = OS.read_string_from_stdin()
if line.is_empty():
break
line = line.strip_edges()
if line.is_empty():
continue
var parts = whitespace.sub(line, " ", true).split(" ", false)
print("true" if inventory.change(parts[0], parts[1]) else "false")
print(inventory.report())
quit()
Spróbuj swoich sił
require_relative 'exercise'
require_relative 'stock'
require_relative 'inventory'
def check(value)
raise 'Public API check failed' unless value
end
s = Stock.new
check(!s.change(-1) && s.quantity == 0 && s.change(4) && !s.change(-5) && s.quantity == 4)
i = Inventory.new
check(!i.change("x", -2) && i.report == "none")
check(i.change("b", 2) && i.change("a", 1) && i.report == "a:1 b:2")
puts solve(STDIN.read)
Wszystkie lekcje w sekcji Ruby dla programistów GDScript
1Zacznij z Ruby
Uruchamianie plików RubyWyjście i komentarzeNazwy i obiektyArytmetyka liczb całkowitychPrawda i logika boolowskaOperacje na łańcuchach znakówSymbole i kluczePodsumowanie: Dowód dostawy2Przepływ i metody
Wartości warunkoweCase i zakresyPętle i wcześniejsze wyjścieMetody i zwracanie wartościWartości domyślne i słowa kluczowePodsumowanie: Uruchomienie czujnika3Kolekcje i bloki
Tablice i indeksowanieHasze i brakujące kluczePrzekazywanie sterowania do blokuMap i SelectReduce i predykatyPodsumowanie: Powtarzający się kodPoćwicz samodzielnie: Kompilator Ruby online