From 9b362a622793763c92fbb444d566bf0e053e9570 Mon Sep 17 00:00:00 2001 From: Isaac Good Date: Thu, 22 Oct 2026 21:42:48 -0700 Subject: [PATCH] [simple-linked-list] Add new practice exercise --- config.json | 8 + .../simple-linked-list/.docs/instructions.md | 19 + .../simple-linked-list/.docs/introduction.md | 5 + .../simple-linked-list/.meta/config.json | 22 + .../simple-linked-list/.meta/example.gd | 56 ++ .../simple-linked-list/.meta/template.j2 | 38 ++ .../simple-linked-list/.meta/tests.toml | 107 ++++ .../simple-linked-list/lib/test_runner.gd | 541 ++++++++++++++++++ .../practice/simple-linked-list/project.godot | 5 + .../practice/simple-linked-list/run_tests | 6 + .../simple-linked-list/simple_linked_list.gd | 22 + .../simple_linked_list_test.gd | 366 ++++++++++++ 12 files changed, 1195 insertions(+) create mode 100644 exercises/practice/simple-linked-list/.docs/instructions.md create mode 100644 exercises/practice/simple-linked-list/.docs/introduction.md create mode 100644 exercises/practice/simple-linked-list/.meta/config.json create mode 100644 exercises/practice/simple-linked-list/.meta/example.gd create mode 100644 exercises/practice/simple-linked-list/.meta/template.j2 create mode 100644 exercises/practice/simple-linked-list/.meta/tests.toml create mode 100644 exercises/practice/simple-linked-list/lib/test_runner.gd create mode 100644 exercises/practice/simple-linked-list/project.godot create mode 100755 exercises/practice/simple-linked-list/run_tests create mode 100644 exercises/practice/simple-linked-list/simple_linked_list.gd create mode 100644 exercises/practice/simple-linked-list/simple_linked_list_test.gd diff --git a/config.json b/config.json index 2b40edb6..365a5404 100644 --- a/config.json +++ b/config.json @@ -471,6 +471,14 @@ "prerequisites": [], "difficulty": 5 }, + { + "slug": "simple-linked-list", + "name": "Simple Linked List", + "uuid": "4a6222cd-3fd8-4f6b-8472-ec9c0696d492", + "practices": [], + "prerequisites": [], + "difficulty": 5 + }, { "slug": "sum-of-multiples", "name": "Sum of Multiples", diff --git a/exercises/practice/simple-linked-list/.docs/instructions.md b/exercises/practice/simple-linked-list/.docs/instructions.md new file mode 100644 index 00000000..04640b1f --- /dev/null +++ b/exercises/practice/simple-linked-list/.docs/instructions.md @@ -0,0 +1,19 @@ +# Instructions + +Write a prototype of the music player application. + +For the prototype, each song will simply be represented by a number. +Given a range of numbers (the song IDs), create a singly linked list. + +Given a singly linked list, you should be able to reverse the list to play the songs in the opposite order. + +~~~~exercism/note +The linked list is a fundamental data structure in computer science, often used in the implementation of other data structures. + +The simplest kind of linked list is a **singly** linked list. +That means that each element (or "node") contains data, along with something that points to the next node in the list. + +If you want to dig deeper into linked lists, check out [this article][intro-linked-list] that explains it using nice drawings. + +[intro-linked-list]: https://medium.com/basecs/whats-a-linked-list-anyway-part-1-d8b7e6508b9d +~~~~ diff --git a/exercises/practice/simple-linked-list/.docs/introduction.md b/exercises/practice/simple-linked-list/.docs/introduction.md new file mode 100644 index 00000000..0e1df72f --- /dev/null +++ b/exercises/practice/simple-linked-list/.docs/introduction.md @@ -0,0 +1,5 @@ +# Introduction + +You work for a music streaming company. + +You've been tasked with creating a playlist feature for your music player application. diff --git a/exercises/practice/simple-linked-list/.meta/config.json b/exercises/practice/simple-linked-list/.meta/config.json new file mode 100644 index 00000000..1306ed06 --- /dev/null +++ b/exercises/practice/simple-linked-list/.meta/config.json @@ -0,0 +1,22 @@ +{ + "authors": [ + "IsaacG" + ], + "files": { + "solution": [ + "simple_linked_list.gd" + ], + "test": [ + "simple_linked_list_test.gd", + "run_tests", + "lib/test_runner.gd", + "project.godot" + ], + "example": [ + ".meta/example.gd" + ] + }, + "blurb": "Write a simple linked list implementation that uses Elements and a List.", + "source": "Inspired by 'Data Structures and Algorithms with Object-Oriented Design Patterns in Ruby', singly linked-lists.", + "source_url": "https://web.archive.org/web/20160731005714/http://brpreiss.com/books/opus8/html/page96.html" +} diff --git a/exercises/practice/simple-linked-list/.meta/example.gd b/exercises/practice/simple-linked-list/.meta/example.gd new file mode 100644 index 00000000..12238535 --- /dev/null +++ b/exercises/practice/simple-linked-list/.meta/example.gd @@ -0,0 +1,56 @@ +class ListNode: + + var value = 0 + var next = null + + func _init(value, next = null): + self.value = value + self.next = next + + +class LinkedList: + + var _head = null + + func _init(values): + for value in values: + push(value) + + func count(): + var cur = _head + var count = 0 + while cur != null: + count += 1 + cur = cur.next + return count + + func push(value): + _head = ListNode.new(value, _head) + + func peek(): + if _head == null: + return null + return _head.value + + func pop(): + if _head == null: + return null + var out = _head.value + _head = _head.next + return out + + func to_list(): + var values = [] + var cur = _head + while cur != null: + values.append(cur.value) + cur = cur.next + values.reverse() + return values + + func reverse(): + var values = to_list() + values.reverse() + _head = null + for value in values: + push(value) diff --git a/exercises/practice/simple-linked-list/.meta/template.j2 b/exercises/practice/simple-linked-list/.meta/template.j2 new file mode 100644 index 00000000..9b85790a --- /dev/null +++ b/exercises/practice/simple-linked-list/.meta/template.j2 @@ -0,0 +1,38 @@ +{% for case in cases %} +func test_{{ case.func_name }}(solution_script): + var linked_list = solution_script.LinkedList.new({{ case.input.initialValues | togdscript }}) + var res = 0 +{% for op in case.input.operations %} +{%- if op.operation == "count" %} + res = linked_list.count() + if res != {{ op.expected }}: + return [false, "count() = %d; expected %d" % [res, {{ op.expected }}]] +{%- elif op.operation == "pop" and op.expected is sequence %} + res = linked_list.pop() + if res != null: + return [false, "pop() = %d; expected null" % res] +{%- elif op.operation == "pop" %} + res = linked_list.pop() + if res != {{ op.expected }}: + return [false, "pop() = %d; expected %d" % [res, {{ op.expected }}]] +{%- elif op.operation == "push" %} + linked_list.push({{ op.value }}) +{%- elif op.operation == "peek" and op.expected is sequence %} + res = linked_list.peek() + if res != null: + return [false, "peek() = %d, expected null" % res] +{%- elif op.operation == "peek" %} + res = linked_list.peek() + if res != {{ op.expected }}: + return [false, "peek() = %d; expected %d" % [res, {{ op.expected }}]] +{%- elif op.operation == "toList" %} + res = linked_list.to_list() + if res != {{ op.expected | togdscript }}: + return [false, "to_list() = %s; expected %s" % [res, {{ op.expected | togdscript }}]] +{%- else %} + linked_list.{{ op.operation }}() +{%- endif %} +{% endfor %} + return [true, true] + +{% endfor %} diff --git a/exercises/practice/simple-linked-list/.meta/tests.toml b/exercises/practice/simple-linked-list/.meta/tests.toml new file mode 100644 index 00000000..59da32f4 --- /dev/null +++ b/exercises/practice/simple-linked-list/.meta/tests.toml @@ -0,0 +1,107 @@ +# This is an auto-generated file. +# +# Regenerating this file via `configlet sync` will: +# - Recreate every `description` key/value pair +# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications +# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion) +# - Preserve any other key/value pair +# +# As user-added comments (using the # character) will be removed when this file +# is regenerated, comments can be added via a `comment` key. + +[962d998c-c203-41e2-8fbd-85a7b98b79b9] +description = "count -> Empty list has length of zero" + +[9760262e-d7e4-4639-9840-87e2e2fbb115] +description = "count -> Singleton list has length of one" + +[d9955c90-637c-441b-b41d-8cfb48e924a8] +description = "count -> Non-empty list has correct length" + +[0c3966db-58f9-4632-b94c-8ea13e54c2c8] +description = "pop -> Pop from empty list is an error" + +[a4f9d2e1-7425-49ef-9ee8-6c0cb3407cf0] +description = "pop -> Can pop from singleton list" + +[6dcbb2c9-d98a-47bc-a010-9c19703d3ea2] +description = "pop -> Can pop from non-empty list" + +[e83aade9-f030-4096-aaf0-f9dc6491e6cf] +description = "pop -> Can pop multiple items" + +[5c46bcf2-c0a9-4654-ae17-f3192436fcf1] +description = "pop -> Pop updates the count" + +[70d747a1-2e84-4ebc-bc3f-dcbee6a05f6b] +description = "push -> Can push to an empty list" +include = false + +[f3197f0a-1fea-45a5-939f-4a5ea60387ec] +description = "push -> Can push to an empty list" +reimplements = "70d747a1-2e84-4ebc-bc3f-dcbee6a05f6b" + +[391e332e-1f91-4033-b1e0-0e0c17812fa7] +description = "push -> Can push to a non-empty list" + +[ed4b0e01-3bbd-4895-af25-152b5914b3da] +description = "push -> Push updates count" + +[41666790-b932-4e5a-b323-e848a83d12d5] +description = "push -> Push and pop" + +[930a4a5c-76f6-47ec-9be3-4e70993173a1] +description = "peek -> Peek on empty list is an error" + +[43255a50-d919-4e81-afce-e4a271eaedbd] +description = "peek -> Can peek on singleton list" + +[48353020-e25d-4621-a854-e35fb1e15fa7] +description = "peek -> Can peek on non-empty list" + +[96fcead9-a713-46c2-8005-3f246c873851] +description = "peek -> Peek does not change the count" + +[7576ed05-7ff7-4b84-8efb-d34d62c110f5] +description = "peek -> Can peek after a pop and push" + +[b97d00b6-2fab-435d-ae74-3233dcc13698] +description = "toList LIFO -> Empty linked list to list is empty" +include = false +comment = "Implements FIFO" + +[eedeb95f-b5cf-431d-8ad6-5854ba6b251c] +description = "toList LIFO -> To list with multiple values" +include = false +comment = "Implements FIFO" + +[838678de-eaf3-4c14-b34e-7e35b6d851e8] +description = "toList LIFO -> To list after a pop" +include = false +comment = "Implements FIFO" + +[03fc83a5-48a8-470b-a2d2-a286c5e8365f] +description = "toList FIFO -> Empty linked list to list is empty" + +[1282484e-a58c-426a-972e-90746bda61fc] +description = "toList FIFO -> To list with multiple values" + +[05ca3109-1249-4c0c-a567-a3b2f8352a7c] +description = "toList FIFO -> To list after a pop" + +[5e6c1a3d-e34b-46d3-be59-3f132a820ed5] +description = "reverse -> Reversed empty list has same values" + +[93c87ed3-862a-474f-820b-ba3fd6b6daf6] +description = "reverse -> Reversed singleton list is same list" + +[92851ebe-9f52-4406-b92e-0718c441a2ab] +description = "reverse -> Reversed non-empty list is reversed" +include = false + +[1210eeda-b23f-4790-930c-7ac6d0c8e723] +description = "reverse -> Reversed non-empty list is reversed" +reimplements = "92851ebe-9f52-4406-b92e-0718c441a2ab" + +[9b53af96-7494-4cfa-9b77-b7366fed5c4c] +description = "reverse -> Double reverse" diff --git a/exercises/practice/simple-linked-list/lib/test_runner.gd b/exercises/practice/simple-linked-list/lib/test_runner.gd new file mode 100644 index 00000000..be91311a --- /dev/null +++ b/exercises/practice/simple-linked-list/lib/test_runner.gd @@ -0,0 +1,541 @@ +class_name TestRunner +extends SceneTree + + +class ErrorReader: + """ErrorReader reads from a STDERR file (cmd 2>/file). + + It filters out the less useful Godot output and handles retrieving lines iteratively. + """ + + const EXPECTED_GODOT_ERRORS = [ + ( + "ERROR: Could not create directory: /root/.local\n" + + " at: make_dir_recursive (core/io/dir_access.cpp:180)\n" + ), + ( + "ERROR: Error attempting to create data dir: " + + "/root/.local/share/godot/app_userdata/[unnamed project].\n" + + " at: ensure_user_data_dir (core/os/os.cpp:344)\n" + ), + ( + "ERROR: Could not create editor data directory: /root/.local/share/godot\n" + + " at: EditorPaths (editor/editor_paths.cpp:183)\n" + ), + ( + "ERROR: Could not create directory: /root/.config\n" + + " at: make_dir_recursive (core/io/dir_access.cpp:180)\n" + ), + ( + "ERROR: Could not create editor config directory: /root/.config/godot\n" + + " at: EditorPaths (editor/editor_paths.cpp:198)\n" + ), + ( + "ERROR: Could not create directory: /root/.cache\n" + + " at: make_dir_recursive (core/io/dir_access.cpp:180)\n" + ), + ( + "ERROR: Could not create editor cache directory: /root/.cache/godot\n" + + " at: EditorPaths (editor/editor_paths.cpp:219)\n" + ), + ( + "ERROR: Can't save resource to empty path. " + + "Provide non-empty path or a Resource with non-empty resource_path.\n" + + " at: save (core/io/resource_saver.cpp:105)\n" + ), + ( + "ERROR: Error saving editor settings to \n" + + " at: save (editor/editor_settings.cpp:1013)\n" + ), + ] + var already_processed_bytes: int = 0 + var filename: String = "" + var color_sequence = RegEx.create_from_string("\\e\\[\\d[\\d;]*m") + + func _init(filename: String) -> void: + self.already_processed_bytes = 0 + self.filename = filename + if not self.filename.is_empty() and ResourceLoader.exists(self.filename): + self.get_error_message() + + func check() -> Error: + if not FileAccess.file_exists(self.filename): + push_error("STDERR must be redirected to '%s' when using '--json'" % self.filename) + return ERR_FILE_NOT_FOUND + if OS.get_stderr_type() != OS.STD_HANDLE_FILE: + push_error("STDERR must be redirected to '%s' when using '--json'" % self.filename) + return ERR_FILE_NOT_FOUND + return OK + + func get_error_message() -> String: + """ + Checks the contents of the STDERR file, where error output from the + currently running test suite should be stored. If there is any relevant output + there, this method will return it. If the file is empty, an empty string is returned. + + This method will remove previously read output from the returned message. It should + be called after executing every test, to ensure that the message contains only output + relevant for the given test. + + NOTE: running a Godot instance without full access to certain folders in the + home directory (`~/.config`, `~/.local`, `~/.cache`) will result in additional + errors. This happens when GDScript test runner is executed in Docker. However, + these errors do not stop the execution of the program, so they can be ignored. + This method filters them out, leaving only the errors caused by the actual tests. + """ + if self.filename.is_empty(): + return "" + + var error_output = FileAccess.get_file_as_string(self.filename) + error_output = error_output.erase(0, self.already_processed_bytes) + self.already_processed_bytes += len(error_output) + + # By default, Godot's error messages are printed with colors. To include the output in the + # `results.json` file, color markers need to be removed first. + error_output = self.color_sequence.sub(error_output, "", true) + + # Filter out the expected error messages + for expected_error in EXPECTED_GODOT_ERRORS: + error_output = error_output.replace(expected_error, "") + + return error_output + + +class ResultWriter: + var json_file: String = "" + var stderr: ErrorReader = null + + func _init(json_file: String, stderr: ErrorReader) -> void: + self.json_file = json_file + self.stderr = stderr + + func delete_existing() -> Error: + """ + Removes the previous `results.json` file, to ensure that the current test suite will not use it. + """ + if self.json_file.is_empty(): + return OK + if FileAccess.file_exists(self.json_file): + DirAccess.remove_absolute(self.json_file) + var error_message: String = self.stderr.get_error_message() + if not error_message.is_empty(): + push_error(error_message) + return FAILED + return OK + + func write(results: Dictionary) -> Error: + """ + If output_dir_path is empty, outputs friendly-formatted test results to + stdout. + + Otherwise, writes JSON results to results.json in the given path. + """ + if self.json_file.is_empty(): + return print_friendly_results(results) + return write_results_file(results) + + func print_friendly_results(results: Dictionary) -> Error: + """ + Prints rich results to stdout. + """ + var rich_results = [""] + if results.status == "pass": + rich_results.push_back("[color=yellow]Exercise passed! Nicely done![/color]") + else: + rich_results.push_back("Exercise has at least one failed test:") + for test in results.tests: + if test.status == "pass": + rich_results.push_back(" %s [color=yellow]passed ✔[/color]" % test.name) + else: + rich_results.push_back( + " %s [color=pink]failed: %s[/color]" % [test.name, test.message] + ) + print_rich("\n".join(rich_results)) + return OK + + func write_results_file(results: Dictionary) -> Error: + """ + Saves a dictionary as a `results.json` file in the output directory. The file + is indented with 4 spaces, keys are not sorted. + + The `results` dictionary represents the full output of a single exercise's + test suite, according to the Test Runner Interface documentation: + + https://exercism.org/docs/building/tooling/test-runners/interface + + This method automatically adds `'version' = 2` to the results. + """ + # Due to keys not being sorted, `version` should be inserted first + var full_results = {"version": 2} + full_results.merge(results) + + var pretty_results = JSON.stringify(full_results, " ", false) + + var results_json = FileAccess.open(self.json_file, FileAccess.WRITE) + if results_json == null: + var err = FileAccess.get_open_error() + push_error("Failed to write the file: %s (%s)" % [self.json_file, error_string(err)]) + return err + + results_json.store_string(pretty_results + "\n") + return OK + + +class ArgParser: + """ArgParser reads the cmdline and parses inputs and options.""" + + var solution_script_path: String = "" + var test_suite_script_path: String = "" + var run_all: bool = false + var json: bool = false + var json_file: String = "" + + func usage(message: String) -> void: + print("Usage:") + print("test_runner [--all] [--json filename.json] ") + if not message.is_empty(): + print() + print(message) + + func parse_args() -> Error: + """ + Validates the number of args passed to the script and sets values of the following + global variables, based on the given args: + * `solution_script_path` + * `test_suite_script_path` + """ + var args = OS.get_cmdline_user_args() + var positional: Array = [] + + var idx := 0 + while idx < len(args): + var arg = args[idx] + if arg == "--all": + run_all = true + elif arg.begins_with("--json"): + if arg.contains("="): + var parts = arg.split("=", true, 1) + if parts[0] == "--json": + self.json = true + self.json_file = parts[1] + else: + usage("Invalid flag %s" % arg) + return ERR_INVALID_PARAMETER + elif idx + 1 < len(args): + self.json = true + self.json_file = args[idx + 1] + idx += 1 + else: + usage("Flag %s is missing a filename" % arg) + return ERR_INVALID_PARAMETER + elif arg.begins_with("--"): + usage("Invalid flag %s" % arg) + return ERR_INVALID_PARAMETER + else: + positional.append(arg) + idx += 1 + + if len(positional) != 2: + usage("Expecting 2 positional args but got %d" % len(positional)) + return ERR_INVALID_PARAMETER + + var slug = positional[0] + var solution_dir_path = positional[1] + + # Test folders use dashes, but test files use underscores + var gdscript_path = solution_dir_path.path_join(slug.replace("-", "_")) + + self.solution_script_path = gdscript_path + ".gd" + self.test_suite_script_path = gdscript_path + "_test.gd" + + return OK + + func files() -> Array: + return [self.solution_script_path, self.test_suite_script_path] + + +class Runner: + var test_suite: Object = null + var solution: Object = null + var stderr: ErrorReader = null + var result_writer: ResultWriter = null + + func _init( + test_suite: Object, solution: Object, stderr: ErrorReader, result_writer: ResultWriter + ) -> void: + self.test_suite = test_suite + self.solution = solution + self.stderr = stderr + self.result_writer = result_writer + + func extract_methods() -> Dictionary: + """Extract the source code of a method from a script.""" + var in_func: bool = false + var parts = [] + var methods: Dictionary = {} + var name: String = "" + var func_re: RegEx = RegEx.create_from_string("^func ([^(]+)\\(") + for line in self.test_suite.get_script().source_code.split("\n"): + if not in_func: + var matched = func_re.search(line) + if matched: + in_func = true + name = matched.get_strings()[1] + parts = [] + elif not line.begins_with("\t") and not line.begins_with(" "): + if in_func: + in_func = false + methods[name] = "\n".join(parts) + else: + parts.append(line) + + return methods + + func get_failed_test_message(actual, expected) -> String: + """ + Generates a message for a failed test. If given values are strings, + this method will wrap them in single quotes, to distinguish from + other types, like integers (e.g. '3' vs 3). + + This method should be used if the actual and expected values for a + given test are different, or if they have different types. + """ + var values = [] + + for value in [actual, expected]: + var formatted_value = str(value) + if typeof(value) == TYPE_STRING: + formatted_value = "'{0}'".format([formatted_value]) + values.append(formatted_value) + + return "Expected output was {1}, actual output was {0}.".format(values) + + func run_tests() -> Array: + """ + Runs the given test suite agains the given solution script. Returns an Array + representing the results of each test case, in the same order that they are defined + in the test suite. Each test result is a Dictionary containing 3 values: + + * `name`: the name of the test case + * `status`: 'pass', 'fail', or 'error' + * `message`: null if the test passed, otherwise it contains the details of the failure/error + + This method will look for methods starting with `test_` in the test script, and + then call them with the solution script as the only argument. The `test_` method's + name will be used as the `name` value for each test result. + + If any stderr output was generated during the execution of the `test_` method, + `status` will be set to 'error'. The test will also receive an 'error' status + if calling the `test_` method returned null (which indicates execution issues). + + Otherwise, the `test_` method should return an Array of 2 elements: the actual value, + and the expected value. The values will be compared and if they are the same, the test will + pass. Otherwise, it will fail, with a relevant message being set by this method. + """ + var test_results = [] + var test_codes = self.extract_methods() + + for method in self.test_suite.get_method_list(): + if not method["name"].begins_with("test_"): + continue + var test_method_name = method["name"] + print("-> " + test_method_name) + var test_method = self.test_suite.get(test_method_name) + + var output = test_method.call(self.solution) + var error_message = self.stderr.get_error_message() + + if output == null: + ( + test_results + . append( + { + "name": test_method_name, + "status": "error", + "message": error_message, + } + ) + ) + else: + var actual = output[0] + var expected = output[1] + + var passed = ( + typeof(actual) == typeof(expected) + and actual == expected + and error_message.is_empty() + ) + + var status = "error" + if error_message.is_empty(): + status = "pass" if passed else "fail" + error_message = ( + null if passed else self.get_failed_test_message(actual, expected) + ) + + var test_code = test_codes[method["name"]] + # The code would be cleaner if the test suite actually checked the values. + # Instead, the test suite returns an array with two values which are compared (above). + # This `replace()` hides some of that implementation detail by communicating that the + # array elements are being compared for equality. + test_code = test_code.replace("return [", "assert_equal [") + test_code = test_code.replace("\t", " ") + test_code = test_code.dedent().strip_edges() + + ( + test_results + . append( + { + "name": test_method_name, + "status": status, + "message": error_message, + "test_code": test_code, + } + ) + ) + + return test_results + + func run(run_all: bool) -> void: + """ + Executes the current suite against the current solution. Stores the results in the + `results.json` file in the output dir. + """ + var test_results = run_tests() + var results = {} + + # Check if any tests were executed + if len(test_results) == 0: + results = {"status": "error", "message": "No tests were executed.", "tests": []} + else: + results = {"status": "pass", "tests": test_results} + + # If any of the tests failed, change the global status to `fail` + for test_result in test_results: + if test_result["status"] != "pass": + results["status"] = "fail" + break + + if not run_all and results["status"] != "pass": + var success_count: int = 0 + for test_result in test_results: + if test_result["status"] == "pass": + success_count += 1 + + var has_failure = false + var filtered_results = [] + for test_result in test_results: + if test_result["status"] == "pass": + filtered_results.append(test_result) + elif not has_failure: + has_failure = true + test_result["message"] = ( + "Passes %d/%d tests. First failure: %s" + % [ + success_count, + len(test_results), + test_result["message"], + ] + ) + filtered_results.append(test_result) + results["tests"] = filtered_results + + self.result_writer.write(results) + + +func load_solution(path: String) -> Object: + """Load a script. This helper is needed to catch failures without aborting the error handling.""" + if not FileAccess.file_exists(path): + return null + var re = RegEx.create_from_string("^( )+") + var replace = RegEx.create_from_string("( )+") + var changed = false + var lines = [] + for line in FileAccess.open(path, FileAccess.READ).get_as_text().split("\n"): + var m = re.search(line) + if m == null: + lines.append(line) + else: + changed = true + var new = [] + for i in range(m.get_end() / 4): + new.append("\t") + new.append(line.substr(m.get_end())) + lines.append("".join(new)) + if not changed: + return load(path).new() + + path = OS.get_temp_dir() + "/solution.gd" + FileAccess.open(path, FileAccess.WRITE).store_string("\n".join(lines)) + var solution = load(path).new() + DirAccess.remove_absolute(path) + return solution + + +func load_solution_script( + solution_script_path: String, result_writer: ResultWriter, stderr: ErrorReader +) -> Array: + """ + Loads the solution script and saves it in a global variable. In case of any + issues, this method will save the `results.json` file with `error` status. + """ + # Make sure the STDERR file is empty. + stderr.get_error_message() + var solution_script = load_solution(solution_script_path) + + if solution_script == null: + var message: String = "The solution file could not be parsed." + # Extract the error message, up until the "Failed to load" line + # which is specific to the test runner, not the user's solution. + var error_message: String = stderr.get_error_message() + if not error_message.is_empty(): + var msg = [] + var stop = ( + 'ERROR: Failed to load script "%s" with error "Parse error".' % solution_script_path + ) + for line in error_message.split("\n"): + if line == stop: + break + msg.append(line) + message += "\n" + "\n".join(msg) + var results = {"status": "error", "message": message, "tests": []} + result_writer.write(results) + return [null, ERR_PARSE_ERROR] + + return [solution_script, OK] + + +func _init(): + # Calling `quit(1)` doesn't stop the program immediately, so a `return` is necessary. + # That's why errors are checked directly in `_init()`, instead of calling `quit(1)` + # in each method. + var args = ArgParser.new() + if args.parse_args() != OK: + quit(1) + return + for file in args.files(): + if not ResourceLoader.exists(file): + push_error("File %s not found." % file) + quit(1) + return + + var stderr = ErrorReader.new("/tmp/stderr") + if args.json and stderr.check() != OK: + quit(1) + return + + var result_writer = ResultWriter.new(args.json_file, stderr) + if result_writer.delete_existing() != OK: + quit(1) + return + + var r = load_solution_script(args.solution_script_path, result_writer, stderr) + if r[1] != OK: + quit(1) + return + var solution = r[0] + + var test_suite = load(args.test_suite_script_path).new() + + Runner.new(test_suite, solution, stderr, result_writer).run(args.run_all) + quit() diff --git a/exercises/practice/simple-linked-list/project.godot b/exercises/practice/simple-linked-list/project.godot new file mode 100644 index 00000000..2474455e --- /dev/null +++ b/exercises/practice/simple-linked-list/project.godot @@ -0,0 +1,5 @@ +config_version=5 + +[application] +config/name="Exercism - Simple Linked List" +config/features=PackedStringArray("4.7") diff --git a/exercises/practice/simple-linked-list/run_tests b/exercises/practice/simple-linked-list/run_tests new file mode 100755 index 00000000..ed18a903 --- /dev/null +++ b/exercises/practice/simple-linked-list/run_tests @@ -0,0 +1,6 @@ +#!/usr/bin/env bash + +slug=${PWD##*/} +[[ -f "${slug//-/_}.gd" ]] || die "Error! solution file is missing" +[[ -f "${slug//-/_}_test.gd" ]] || die "Error! test file is missing" +exec godot --headless --script ./lib/test_runner.gd -- "${slug}" "${PWD}" diff --git a/exercises/practice/simple-linked-list/simple_linked_list.gd b/exercises/practice/simple-linked-list/simple_linked_list.gd new file mode 100644 index 00000000..1189d473 --- /dev/null +++ b/exercises/practice/simple-linked-list/simple_linked_list.gd @@ -0,0 +1,22 @@ +class LinkedList: + + func _init(values): + pass + + func count(): + pass + + func push(value): + pass + + func peek(): + pass + + func pop(): + pass + + func to_list(): + pass + + func reverse(): + pass diff --git a/exercises/practice/simple-linked-list/simple_linked_list_test.gd b/exercises/practice/simple-linked-list/simple_linked_list_test.gd new file mode 100644 index 00000000..9dad710c --- /dev/null +++ b/exercises/practice/simple-linked-list/simple_linked_list_test.gd @@ -0,0 +1,366 @@ +func test_empty_list_has_length_of_zero(solution_script): + var linked_list = solution_script.LinkedList.new([]) + var res = 0 + + res = linked_list.count() + if res != 0: + return [false, "count() = %d; expected %d" % [res, 0]] + + return [true, true] + + +func test_singleton_list_has_length_of_one(solution_script): + var linked_list = solution_script.LinkedList.new([1]) + var res = 0 + + res = linked_list.count() + if res != 1: + return [false, "count() = %d; expected %d" % [res, 1]] + + return [true, true] + + +func test_non_empty_list_has_correct_length(solution_script): + var linked_list = solution_script.LinkedList.new([1, 2, 3]) + var res = 0 + + res = linked_list.count() + if res != 3: + return [false, "count() = %d; expected %d" % [res, 3]] + + return [true, true] + + +func test_pop_from_empty_list_is_an_error(solution_script): + var linked_list = solution_script.LinkedList.new([]) + var res = 0 + + res = linked_list.pop() + if res != null: + return [false, "pop() = %d; expected null" % res] + + return [true, true] + + +func test_can_pop_from_singleton_list(solution_script): + var linked_list = solution_script.LinkedList.new([1]) + var res = 0 + + res = linked_list.pop() + if res != 1: + return [false, "pop() = %d; expected %d" % [res, 1]] + + return [true, true] + + +func test_can_pop_from_non_empty_list(solution_script): + var linked_list = solution_script.LinkedList.new([1, 2]) + var res = 0 + + res = linked_list.pop() + if res != 2: + return [false, "pop() = %d; expected %d" % [res, 2]] + + return [true, true] + + +func test_can_pop_multiple_items(solution_script): + var linked_list = solution_script.LinkedList.new([1, 2]) + var res = 0 + + res = linked_list.pop() + if res != 2: + return [false, "pop() = %d; expected %d" % [res, 2]] + + res = linked_list.pop() + if res != 1: + return [false, "pop() = %d; expected %d" % [res, 1]] + + return [true, true] + + +func test_pop_updates_the_count(solution_script): + var linked_list = solution_script.LinkedList.new([1, 2]) + var res = 0 + + res = linked_list.count() + if res != 2: + return [false, "count() = %d; expected %d" % [res, 2]] + + res = linked_list.pop() + if res != 2: + return [false, "pop() = %d; expected %d" % [res, 2]] + + res = linked_list.count() + if res != 1: + return [false, "count() = %d; expected %d" % [res, 1]] + + res = linked_list.pop() + if res != 1: + return [false, "pop() = %d; expected %d" % [res, 1]] + + res = linked_list.count() + if res != 0: + return [false, "count() = %d; expected %d" % [res, 0]] + + return [true, true] + + +func test_can_push_to_an_empty_list(solution_script): + var linked_list = solution_script.LinkedList.new([]) + var res = 0 + + linked_list.push(1) + + return [true, true] + + +func test_can_push_to_a_non_empty_list(solution_script): + var linked_list = solution_script.LinkedList.new([1, 2]) + var res = 0 + + linked_list.push(3) + + return [true, true] + + +func test_push_updates_count(solution_script): + var linked_list = solution_script.LinkedList.new([1, 2]) + var res = 0 + + linked_list.push(3) + + res = linked_list.count() + if res != 3: + return [false, "count() = %d; expected %d" % [res, 3]] + + return [true, true] + + +func test_push_and_pop(solution_script): + var linked_list = solution_script.LinkedList.new([]) + var res = 0 + + linked_list.push(1) + + linked_list.push(2) + + res = linked_list.pop() + if res != 2: + return [false, "pop() = %d; expected %d" % [res, 2]] + + linked_list.push(3) + + res = linked_list.count() + if res != 2: + return [false, "count() = %d; expected %d" % [res, 2]] + + res = linked_list.pop() + if res != 3: + return [false, "pop() = %d; expected %d" % [res, 3]] + + res = linked_list.pop() + if res != 1: + return [false, "pop() = %d; expected %d" % [res, 1]] + + res = linked_list.count() + if res != 0: + return [false, "count() = %d; expected %d" % [res, 0]] + + return [true, true] + + +func test_peek_on_empty_list_is_an_error(solution_script): + var linked_list = solution_script.LinkedList.new([]) + var res = 0 + + res = linked_list.peek() + if res != null: + return [false, "peek() = %d, expected null" % res] + + return [true, true] + + +func test_can_peek_on_singleton_list(solution_script): + var linked_list = solution_script.LinkedList.new([1]) + var res = 0 + + res = linked_list.peek() + if res != 1: + return [false, "peek() = %d; expected %d" % [res, 1]] + + return [true, true] + + +func test_can_peek_on_non_empty_list(solution_script): + var linked_list = solution_script.LinkedList.new([1, 2]) + var res = 0 + + res = linked_list.peek() + if res != 2: + return [false, "peek() = %d; expected %d" % [res, 2]] + + return [true, true] + + +func test_peek_does_not_change_the_count(solution_script): + var linked_list = solution_script.LinkedList.new([1, 2]) + var res = 0 + + res = linked_list.peek() + if res != 2: + return [false, "peek() = %d; expected %d" % [res, 2]] + + res = linked_list.count() + if res != 2: + return [false, "count() = %d; expected %d" % [res, 2]] + + return [true, true] + + +func test_can_peek_after_a_pop_and_push(solution_script): + var linked_list = solution_script.LinkedList.new([]) + var res = 0 + + linked_list.push(1) + + linked_list.push(2) + + res = linked_list.peek() + if res != 2: + return [false, "peek() = %d; expected %d" % [res, 2]] + + res = linked_list.pop() + if res != 2: + return [false, "pop() = %d; expected %d" % [res, 2]] + + res = linked_list.peek() + if res != 1: + return [false, "peek() = %d; expected %d" % [res, 1]] + + linked_list.push(3) + + res = linked_list.peek() + if res != 3: + return [false, "peek() = %d; expected %d" % [res, 3]] + + return [true, true] + + +func test_empty_linked_list_to_list_is_empty(solution_script): + var linked_list = solution_script.LinkedList.new([]) + var res = 0 + + res = linked_list.to_list() + if res != []: + return [false, "to_list() = %s; expected %s" % [res, []]] + + return [true, true] + + +func test_to_list_with_multiple_values(solution_script): + var linked_list = solution_script.LinkedList.new([1, 2, 3]) + var res = 0 + + res = linked_list.to_list() + if res != [1, 2, 3]: + return [false, "to_list() = %s; expected %s" % [res, [1, 2, 3]]] + + return [true, true] + + +func test_to_list_after_a_pop(solution_script): + var linked_list = solution_script.LinkedList.new([]) + var res = 0 + + linked_list.push(1) + + linked_list.push(2) + + linked_list.push(3) + + res = linked_list.pop() + if res != 3: + return [false, "pop() = %d; expected %d" % [res, 3]] + + linked_list.push(4) + + res = linked_list.to_list() + if res != [1, 2, 4]: + return [false, "to_list() = %s; expected %s" % [res, [1, 2, 4]]] + + return [true, true] + + +func test_reversed_empty_list_has_same_values(solution_script): + var linked_list = solution_script.LinkedList.new([]) + var res = 0 + + linked_list.reverse() + + res = linked_list.to_list() + if res != []: + return [false, "to_list() = %s; expected %s" % [res, []]] + + return [true, true] + + +func test_reversed_singleton_list_is_same_list(solution_script): + var linked_list = solution_script.LinkedList.new([1]) + var res = 0 + + linked_list.reverse() + + res = linked_list.to_list() + if res != [1]: + return [false, "to_list() = %s; expected %s" % [res, [1]]] + + return [true, true] + + +func test_reversed_non_empty_list_is_reversed(solution_script): + var linked_list = solution_script.LinkedList.new([1, 2, 3]) + var res = 0 + + linked_list.reverse() + + res = linked_list.count() + if res != 3: + return [false, "count() = %d; expected %d" % [res, 3]] + + res = linked_list.pop() + if res != 1: + return [false, "pop() = %d; expected %d" % [res, 1]] + + res = linked_list.pop() + if res != 2: + return [false, "pop() = %d; expected %d" % [res, 2]] + + res = linked_list.pop() + if res != 3: + return [false, "pop() = %d; expected %d" % [res, 3]] + + return [true, true] + + +func test_double_reverse(solution_script): + var linked_list = solution_script.LinkedList.new([1, 2, 3]) + var res = 0 + + linked_list.reverse() + + linked_list.reverse() + + res = linked_list.pop() + if res != 3: + return [false, "pop() = %d; expected %d" % [res, 3]] + + res = linked_list.pop() + if res != 2: + return [false, "pop() = %d; expected %d" % [res, 2]] + + res = linked_list.pop() + if res != 1: + return [false, "pop() = %d; expected %d" % [res, 1]] + + return [true, true]