Menu
CoddyTech

Sorting Copies

Lesson 39 of 48 in Coddy's GDScript for Go Developers course.

Go sort.Slice and GDScript sort_custom both use Boolean ordering predicates, but Go passes element indices while GDScript passes values. Access the correct source elements before comparing. Both mutate their sequence, so copy outer storage first when preserving caller order is required. Keep the relation strict and consistent. A three-way numeric result is not the required Boolean contract. The example orders positive integers by their final digit, leaving lexical task sorting to implement.

Complete Go comparison. Save the listed files in one directory and run all .go files together; package main supplies the entry point.

Go file main.go:

package main
import ("fmt" ; "sort")

func main() { items:=[]int{24,11,32}; sort.Slice(items,func(i,j int) bool { return items[i]%10<items[j]%10 }); fmt.Printf("%d,%d,%d\n",items[0],items[1],items[2]) }

Go output:

11,32,24

GDScript example file main.gd:

extends Node

func _ready() -> void:
	var items: Array = [24,11,32]
	items.sort_custom(func(a, b) -> bool: return int(a)%10 < int(b)%10)
	print("%d,%d,%d" % items)

GDScript output:

11,32,24
challenge icon

Challenge

Easy

Implement SortWords.ordered(words:Array)->Array returning an independent lexicographically sorted outer copy. Words are lowercase ASCII. Solve joins with commas or returns none. Locked probes ensure caller storage is unchanged.

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 sort_words.gd, 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:
	var words: Array = ["z","a"]
	var result: Array = SortWords.ordered(words)
	if result != ["a","z"] or words != ["z","a"]: return false
	result.append("x")
	if words.size() != 2: return false
	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))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in GDScript for Go Developers

Practice on your own: Online GDScript compiler