Final : Port d’inventaire
Leçon 47 sur 48 du cours GDScript pour les développeurs Java de Coddy.
Défi
FacileTransposez la référence Java : prenez des mots en entrée, renvoyez des paires mot=nombre triées par ordre alphabétique et séparées par des virgules, ou none. Les mots sont en minuscules et en ASCII, et les doublons sont comptés séparément. Ne modifiez pas l’entrée de l’appelant.
L’entrée est un tableau JSON sur stdin. Le main verrouillé l’analyse, appelle les API publiques et affiche result= suivi du texte renvoyé et d’un retour à la ligne. Aucun utilitaire ne doit afficher quoi que ce soit. Des tests fixes indépendants vérifient le comportement requis de l’API avant le cas d’entrée ; ils n’imposent pas de style d’implémentation.
Référence Java complète. Compilez les fichiers .java indiqués ensemble avec Java 17, puis exécutez Main. Le programme lit le même tableau JSON et affiche le même protocole de résultat en utilisant uniquement les classes de la bibliothèque standard.
Fichier Java Inventory.java :
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;
public class Inventory {
public static String summarize(List<String> words) {
Map<String,Integer> counts=new TreeMap<>();
for(String word:words) counts.merge(word,1,Integer::sum);
List<String> parts=new ArrayList<>();
for(var entry:counts.entrySet()) parts.add(entry.getKey()+"="+entry.getValue());
return parts.isEmpty()?"none":String.join(",",parts);
}
}
Fichier Java Main.java :
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class Main {
// Parser for the contract's JSON array of lowercase ASCII words.
private final String text;
private int at=0;
private Main(String text) { this.text=text; }
private char peek() { return at<text.length()?text.charAt(at):0; }
private char take() {
if(at==text.length()) throw new IllegalArgumentException("unexpected end");
return text.charAt(at++);
}
private void space() {
while(peek()==' ' || peek()=='\t' || peek()=='\r' || peek()=='\n') ++at;
}
private String word() {
if(take()!='"') throw new IllegalArgumentException("expected string");
StringBuilder out=new StringBuilder();
while(peek()!='"') {
int value=take();
if(value=='\\') {
if(take()!='u') throw new IllegalArgumentException("expected escape");
value=0;
for(int i=0;i<4;++i) {
int h=Character.digit(take(),16);
if(h<0) throw new IllegalArgumentException("invalid escape");
value=value*16+h;
}
}
if(value<'a' || value>'z') throw new IllegalArgumentException("expected lowercase ASCII");
out.append((char)value);
}
take();
return out.toString();
}
private List<String> parse() {
space();
if(take()!='[') throw new IllegalArgumentException("expected array");
space();
List<String> words=new ArrayList<>();
if(peek()!=']') {
for(;;) {
words.add(word()); space();
if(peek()==']') break;
if(take()!=',') throw new IllegalArgumentException("expected comma");
space();
}
}
take(); space();
if(at!=text.length()) throw new IllegalArgumentException("trailing input");
return words;
}
public static void main(String[] args) throws IOException {
String input=new String(System.in.readAllBytes(),StandardCharsets.UTF_8);
System.out.println("result="+Inventory.summarize(new Main(input).parse()));
}
}
Votre code va dans exercise.gd. main.gd contient le code fourni pour l’entrée et la sortie et ne peut pas être modifié. Placez chaque type class_name dans le fichier portant son nom.
Essayez vous-même
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))
Toutes les leçons de GDScript pour les développeurs Java
1Scripts et valeurs scalaires
Exécuter des fichiers de scriptTexte et commentairesAffectations et typesArithmétique entièreRésultats booléensRécapitulatif : étiquette de stock2Flux et fonctions
Branches et valeursCorrespondance de motifsBoucles et plagesFonctions typéesArguments par défautRécapitulatif : nombre de commandes3Propriété des collections
Opérations sur les tableauxTableaux typésTableaux partagés et copiésPrésence dans un dictionnaireParcours d’un dictionnaireRécapitulatif : fréquences des motsEntraînez-vous par vous-même : Compilateur GDScript en ligne