Bài cuối: Chuyển đổi cảm biến
Bài học 48 trên 48 trong khóa học Ruby dành cho lập trình viên GDScript của Coddy.
Thử thách
DễChuyển chương trình tham chiếu sang Ruby. Above(limit)#accept?(n) chấp nhận n nếu n lớn hơn limit. Sensor(policy)#feed(token) phân tích token gồm một dấu tùy chọn theo sau bởi một hoặc nhiều chữ số ASCII, không có khoảng trắng hay ký tự nào khác, và chỉ chấp nhận số nguyên từ -1000000 đến 1000000. Token không hợp lệ làm tăng invalid; token hợp lệ được policy chấp nhận làm tăng accepted và cộng vào total. Token hợp lệ bị từ chối không làm thay đổi bộ đếm nào. summary trả về accepted, invalid, total, cách nhau bằng khoảng trắng. Dòng đầu tiên của đầu vào là limit; mỗi dòng còn lại là một token, đã loại bỏ ký tự kết thúc dòng. Cả ba bộ đếm bắt đầu từ 0. Các đối tượng policy tùy chỉnh phải hoạt động.
Trả về văn bản từ solve(input) mà không in ra. Driver bị khóa sẽ in văn bản được trả về kèm một ký tự xuống dòng cuối cùng và kiểm tra riêng các API công khai bắt buộc.
Đặt code của bạn trong exercise.rb, above.rb, sensor.rb. main.rb chứa code đầu vào/đầu ra được cung cấp và không thể chỉnh sửa.
Chương trình tham chiếu GDScript. Hãy làm cho chương trình Ruby khớp với hành vi của nó bằng các API Ruby bắt buộc.
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
func sensor_lines() -> PackedStringArray:
var bytes = PackedByteArray()
while true:
var chunk = OS.read_buffer_from_stdin(4096)
if chunk.is_empty():
break
bytes.append_array(chunk)
# String decoding truncates at NUL. Preserve its invalid-token meaning.
for index in range(bytes.size()):
if bytes[index] == 0:
bytes[index] = 35
var text = bytes.get_string_from_utf8()
var lines = PackedStringArray()
var start = 0
var i = 0
while i < text.length():
var unit = text.unicode_at(i)
if unit in [10, 13, 11, 12, 28, 29, 30, 133, 8232, 8233]:
lines.append(text.substr(start, i - start))
if unit == 13 and i + 1 < text.length() and text.unicode_at(i + 1) == 10:
i += 1
start = i + 1
i += 1
if start < text.length():
lines.append(text.substr(start))
return lines
class Above:
var limit: int
func _init(value: int):
limit = value
func accepts(value: int) -> bool:
return value > limit
class Sensor:
var policy
var accepted = "0"
var invalid = "0"
var total = "0"
func _init(value):
policy = value
func parse(token: String):
var i = 0
var negative = false
if i < token.length() and (token[i] == "+" or token[i] == "-"):
negative = token[i] == "-"
i += 1
if i == token.length():
return null
var value = 0
while i < token.length():
var digit = token.unicode_at(i) - 48
if digit < 0 or digit > 9:
return null
value = value * 10 + digit
if value > 1000000:
return null
i += 1
return -value if negative else value
func feed(token: String):
var value = parse(token)
if value == null:
invalid = Decimal.add(invalid, "1")
elif policy.accepts(value):
accepted = Decimal.add(accepted, "1")
total = Decimal.add(total, str(value))
func summary() -> String:
return accepted + " " + invalid + " " + total
func _init():
var lines = sensor_lines()
var limit_text = Decimal.normalize(lines[0].strip_edges())
var negative = limit_text.begins_with("-")
var magnitude = limit_text.substr(1) if negative else limit_text
var limit = int(limit_text)
if Decimal.compare_abs(magnitude, "1000000") > 0:
limit = -1000001 if negative else 1000000
var sensor = Sensor.new(Above.new(limit))
for i in range(1, lines.size()):
sensor.feed(lines[i])
print(sensor.summary())
quit()
Tự làm thử
require_relative 'exercise'
require_relative 'above'
require_relative 'sensor'
def check(value)
raise 'Public API check failed' unless value
end
check(Above.new(4).accept?(5) && !Above.new(4).accept?(4))
policy = Object.new
def policy.accept?(n); n.even?; end
s = Sensor.new(policy)
["2", "-4", "3", "x", "4\n", "1000001"].each { |t| s.feed(t) }
check(s.summary == "2 3 -2" && s.summary == "2 3 -2")
puts solve(STDIN.read)
Tất cả bài học trong Ruby dành cho lập trình viên GDScript
1Bắt đầu với Ruby
Chạy tệp RubyĐầu ra và chú thíchTên và đối tượngPhép toán số nguyênGiá trị đúng sai và logic BooleanThao tác với chuỗiSymbol và khóaÔn tập: Phiếu đóng gói2Luồng và phương thức
Giá trị điều kiệnTrường hợp và khoảng giá trịVòng lặp và thoát sớmPhương thức và giá trị trả vềGiá trị mặc định và từ khóaÔn tập: Chạy cảm biến5Đối tượng và trạng thái
Module làm không gian tênLớp và instanceTrình đọc và trình ghiKhởi tạo có xác thựcÔn tập: VíTự luyện tập: Trình biên dịch Ruby online