|
| 1 | +extends Node |
| 2 | + |
| 3 | +const spellings = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] |
| 4 | + |
| 5 | +func _init() -> void: |
| 6 | + # Trials. |
| 7 | + print("\nTrials:") |
| 8 | + assert(run("res://day_01/example_1.txt") == 142) |
| 9 | + assert(run("res://day_01/example_1.txt", true) == 142) |
| 10 | + assert(run("res://day_01/example_2.txt") == 577) |
| 11 | + assert(run("res://day_01/example_2.txt", true) == 671) |
| 12 | + assert(run("res://day_01/example_3.txt", true) == 281) |
| 13 | + assert(run("res://day_01/example_4.txt", true) == 26) |
| 14 | + assert(run("res://day_01/example_5.txt", true) == 282) |
| 15 | + |
| 16 | + # Challenges. |
| 17 | + print("\nPuzzle 1:") |
| 18 | + assert(run("res://day_01/input.txt") == 52974) |
| 19 | + assert(run("res://day_01/input.txt", true) == 53340) |
| 20 | + |
| 21 | +func spelling_to_digit(spelling: String) -> String: |
| 22 | + var index = spellings.find(spelling) |
| 23 | + return str(index + 1) |
| 24 | + |
| 25 | +func match_spelling_at_start(line: String, offset: int) -> String: |
| 26 | + for spelling in spellings: |
| 27 | + if line.substr(offset).begins_with(spelling): |
| 28 | + return spelling |
| 29 | + |
| 30 | + return "" |
| 31 | + |
| 32 | +func match_spelling_at_end(line: String, offset: int) -> String: |
| 33 | + for spelling in spellings: |
| 34 | + if line.substr(0, offset + 1).ends_with(spelling): |
| 35 | + return spelling |
| 36 | + |
| 37 | + return "" |
| 38 | + |
| 39 | +func run(path: String, use_spellings: bool = false) -> int: |
| 40 | + var file = FileAccess.open(path, FileAccess.READ) |
| 41 | + assert(file, "Failed to read file") |
| 42 | + |
| 43 | + var sum: int = 0 |
| 44 | + var line: String = file.get_line() |
| 45 | + |
| 46 | + while line: |
| 47 | + var first_digit: String |
| 48 | + var last_digit: String |
| 49 | + |
| 50 | + for index in line.length(): |
| 51 | + var reverse_index = (line.length() - 1) - index |
| 52 | + |
| 53 | + var start_char = line[index] |
| 54 | + var end_char = line[reverse_index] |
| 55 | + |
| 56 | + if not first_digit and start_char.is_valid_int(): |
| 57 | + first_digit = start_char |
| 58 | + |
| 59 | + if not last_digit and end_char.is_valid_int(): |
| 60 | + last_digit = end_char |
| 61 | + |
| 62 | + if use_spellings: |
| 63 | + var start_spelling_match = match_spelling_at_start(line, index) |
| 64 | + var end_spelling_match = match_spelling_at_end(line, reverse_index) |
| 65 | + |
| 66 | + if not first_digit and start_spelling_match: |
| 67 | + first_digit = spelling_to_digit(start_spelling_match) |
| 68 | + |
| 69 | + if not last_digit and end_spelling_match: |
| 70 | + last_digit = spelling_to_digit(end_spelling_match) |
| 71 | + |
| 72 | + if first_digit and last_digit: |
| 73 | + break |
| 74 | + |
| 75 | + sum += int(first_digit + last_digit) |
| 76 | + line = file.get_line() |
| 77 | + |
| 78 | + print(sum) |
| 79 | + return sum |
0 commit comments