GDScript 장부 포팅하기
Coddy의 GDScript 개발자를 위한 JavaScript 코스 레슨. 48개 중 47번째.
챌린지
쉬움함께 제공된 GDScript 참조 프로그램을 JavaScript로 포팅하세요. 입력은 [name,quantity] 쌍의 배열입니다. 이름은 문자열이고 수량은 정수입니다. 이름별로 수량을 합산하고, 양수인 합계만 유지하고, 이름을 ASCII 순서로 정렬한 다음 [name,total] 쌍을 반환하세요. 프로토타입과 비슷한 이름도 처리할 수 있도록 Map을 사용하세요. 이름에는 ASCII 문자만 포함됩니다.
GDScript 참조 프로그램입니다. 완전한 Node 스크립트는 JSON 값 하나를 읽고 JSON을 출력합니다. 파싱된 숫자는 명시된 안전한 정수 범위 내에서 int로 변환되며, 정수 합계는 십진수 텍스트로 출력됩니다. Godot 문자열은 NUL을 거부하므로, 이스케이프된 0바이트는 파싱 중 비 ASCII 플레이스홀더를 사용하고, 비교할 때는 0으로 취급하며 JSON 출력 시 원래 값으로 복원합니다. ASCII 입력 이름은 해당 플레이스홀더와 충돌할 수 없습니다.
extends Node
# Godot String rejects NUL, so preserve it through a non-ASCII placeholder.
# Input names are ASCII, which makes this placeholder unambiguous.
const ZERO_PLACEHOLDER: int = 0xE000
func protect_zero_escapes(text: String) -> String:
var result: String = ""
var i: int = 0
while i<text.length():
if text[i]=="\\" and i+1<text.length():
if text.substr(i,6)=="\\u0000":
result+="\\uE000"
i+=6
else:
result+=text.substr(i,2)
i+=2
else:
result+=text[i]
i+=1
return result
func ascii_less(a: String,b: String) -> bool:
for i in range(mini(a.length(),b.length())):
var left: int = a.unicode_at(i)
var right: int = b.unicode_at(i)
if left==ZERO_PLACEHOLDER:
left=0
if right==ZERO_PLACEHOLDER:
right=0
if left!=right:
return left<right
return a.length()<b.length()
func encode_name(value: String) -> String:
var result: String = "\""
for i in range(value.length()):
var codepoint: int = value.unicode_at(i)
if codepoint==ZERO_PLACEHOLDER:
codepoint=0
match codepoint:
34: result+="\\\""
92: result+="\\\\"
8: result+="\\b"
9: result+="\\t"
10: result+="\\n"
12: result+="\\f"
13: result+="\\r"
_:
if codepoint<32:
result+="\\u%04x" % codepoint
else:
result+=String.chr(codepoint)
return result+"\""
func _ready() -> void:
var chunks: PackedStringArray = []
while true:
var line: String = OS.read_string_from_stdin()
if line.is_empty():
break
chunks.append(line)
var rows: Array = JSON.parse_string(protect_zero_escapes("\n".join(chunks)))
var totals: Dictionary = {}
for row: Array in rows:
var item: String = str(row[0])
totals[item]=int(totals.get(item,0))+int(row[1])
var names: Array = totals.keys()
names.sort_custom(ascii_less)
var result: PackedStringArray = []
for item: String in names:
if int(totals[item])>0:
var encoded: String = encode_name(item)
result.append("["+encoded+","+str(int(totals[item]))+"]")
print("["+ ",".join(result)+"]")
입력은 JSON 값 하나입니다. 잠금 해제된 파일을 수정하세요. exercise.js부터 시작하세요. 화면에 보이는 잠긴 driver.js는 solve(input)을 호출하고, 반환값을 한 개의 줄바꿈 문자 뒤에 이어지는 압축 JSON으로 출력합니다. 진단 출력을 추가하지 마세요. 테스트에서는 전체 출력을 비교합니다. 모든 숫자 입력과 계산된 정수 합계는 안전한 정수 범위 안에 있습니다.
입력 예시:
[["pen",3],["book",1],["pen",-1]]예상 출력:
[["book",1],["pen",2]]직접 해보기
import { readFileSync } from "node:fs";
import { solve } from "./exercise.js";
// stdin으로 JSON 값 하나가 들어옵니다. 데이터를 반환하고, solve 내부에서는 출력하지 마세요.
const input = JSON.parse(readFileSync(0,"utf8"));
console.log(JSON.stringify(solve(input)));
GDScript 개발자를 위한 JavaScript의 모든 레슨
직접 연습해 보세요: 온라인 JavaScript 컴파일러