Menu
CoddyTech

Final: Inventory Port

Lesson 47 of 48 in Coddy's GDScript for Rust Developers course.

challenge icon

Challenge

Easy

Port the Rust 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.

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.

Input bounds: at most 1000 lowercase ASCII words. The Rust reference borrows an immutable slice and leaves caller storage unchanged.

Complete Rust reference program. It reads the same JSON array from stdin and writes the same result line:

Rust file inventory.rs:

use std::collections::BTreeMap;
pub fn inventory(words:&[String])->String {
    let mut counts:BTreeMap<&str,usize>=BTreeMap::new();
    for word in words { *counts.entry(word.as_str()).or_insert(0)+=1; }
    if counts.is_empty() { return "none".into(); }
    counts.iter().map(|(word,count)|format!("{word}={count}")).collect::<Vec<_>>().join(",")
}

Rust file main.rs:

mod inventory;
use std::io::{self,Read};
struct Words<'a> { bytes:&'a [u8], at:usize }
impl<'a> Words<'a> {
    fn peek(&self)->Option<u8> { self.bytes.get(self.at).copied() }
    fn take(&mut self)->u8 { let ch=self.peek().expect("unexpected end"); self.at+=1; ch }
    fn space(&mut self) { while matches!(self.peek(),Some(b' '|b'\n'|b'\r'|b'\t')) { self.at+=1; } }
    fn word(&mut self)->String {
        assert_eq!(self.take(),b'"');
        let mut out=String::new();
        while self.peek()!=Some(b'"') {
            let mut ch=self.take() as u32;
            if ch==b'\\' as u32 {
                assert_eq!(self.take(),b'u'); ch=0;
                for _ in 0..4 { ch=ch*16+(self.take() as char).to_digit(16).expect("hex"); }
            }
            assert!((b'a' as u32..=b'z' as u32).contains(&ch));
            out.push(char::from_u32(ch).expect("ASCII"));
        }
        self.take(); out
    }
    fn parse(&mut self)->Vec<String> {
        self.space(); assert_eq!(self.take(),b'['); self.space();
        let mut out=Vec::new();
        if self.peek()!=Some(b']') {
            loop {
                out.push(self.word()); self.space();
                if self.peek()==Some(b']') { break; }
                assert_eq!(self.take(),b','); self.space();
            }
        }
        self.take(); self.space(); assert_eq!(self.at,self.bytes.len()); out
    }
}
fn main() {
    let mut input=String::new(); io::stdin().read_to_string(&mut input).expect("stdin");
    let words=Words{bytes:input.as_bytes(),at:0}.parse();
    println!("result={}",inventory::inventory(&words));
}

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 Rust Developers

Practice on your own: Online GDScript compiler