Final: Inventory Port
Lesson 47 of 48 in Coddy's GDScript for Go Developers course.
Challenge
EasyPort the Go reference: input words, return alphabetically sorted word=count pairs joined by commas, or none. Words are lowercase ASCII, duplicates count separately. Do not change caller input.
Input is one JSON array on stdin. The locked main parses it, calls the public APIs and prints result= followed by the returned text and a newline. No helper should print. Independent fixed probes verify required API behavior before the input case; they do not enforce implementation style.
Complete Go reference. Save the listed files in one directory and run all .go files together. The main package reads the same JSON array and prints the same result protocol. Only standard-library packages are used.
Go file inventory.go:
package main
import ("sort"; "strconv"; "strings")
func inventory(words []string) string {
counts:=make(map[string]int)
for _,word:=range words { counts[word]++ }
keys:=make([]string,0,len(counts))
for word:=range counts { keys=append(keys,word) }
sort.Strings(keys)
parts:=make([]string,0,len(keys))
for _,word:=range keys { parts=append(parts,word+"="+strconv.Itoa(counts[word])) }
if len(parts)==0 { return "none" }
return strings.Join(parts,",")
}
Go file main.go:
package main
import ("encoding/json"; "fmt"; "os")
func main() {
var words []string
if err:=json.NewDecoder(os.Stdin).Decode(&words); err!=nil { panic(err) }
fmt.Println("result="+inventory(words))
}
Your code goes in exercise.gd. main.gd holds the supplied input/output code and cannot be edited. Keep each class_name type in its named file.
Try it yourself
extends Node
func contract_ok(data: Array) -> bool:
return true
func _ready() -> void:
var data: Array = JSON.parse_string(OS.read_string_from_stdin())
if not contract_ok(data):
print("API_CONTRACT_FAILED")
return
print("result=" + Exercise.solve(data))
All lessons in GDScript for Go Developers
1Scripts and Scalar Values
Run Script FilesText and CommentsBindings and TypesInteger ArithmeticBoolean ResultsRecap: Stock Label2Flow and Functions
Branches and ValuesPattern MatchingLoops and RangesTyped FunctionsDefault ArgumentsRecap: Command CountPractice on your own: Online GDScript compiler