From aa0f725e19787255a3464b81c6041f52dda3a768 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hugo=20M=C3=A5rdbrink?= Date: Tue, 2 Dec 2025 09:31:56 +0100 Subject: [PATCH] Day 2 --- .gitignore | 3 ++ d02/main.odin | 88 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 d02/main.odin diff --git a/.gitignore b/.gitignore index 2250ff0..874382e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,5 @@ # Hide inputs *.txt + +# Build files +*.dSYM diff --git a/d02/main.odin b/d02/main.odin new file mode 100644 index 0000000..28662ca --- /dev/null +++ b/d02/main.odin @@ -0,0 +1,88 @@ +package main + +import "core:fmt" +import "core:math" +import "core:os" +import "core:slice" +import "core:strconv" +import "core:strings" +import "core:time" + +import util "../util" + +part_1 :: proc(lines: ^[]string) { + result: i64 = 0 + + buf: [100]byte + for line in lines { + range := strings.split(line, "-") + lower, _ := strconv.parse_i64(range[0]) + upper, _ := strconv.parse_i64(range[1]) + + for id in lower ..= upper { + id_str := strconv.write_int(buf[:], id, 10) + half_len := len(id_str) / 2 + equal_parts := id_str[:half_len] == id_str[half_len:] + + result += id if equal_parts else 0 + } + } + + fmt.printfln(" [Result] %v", result) +} + +has_recurring_segments :: proc(id: i64) -> bool { + buf: [100]byte + id_str := strconv.write_int(buf[:], id, 10) + + for seg_len in 1 ..= len(id_str) / 2 { + if len(id_str) % seg_len != 0 do continue + + matching_pattern := true + for i in seg_len ..< len(id_str) { + if id_str[i] != id_str[i % seg_len] { + matching_pattern = false + break + } + } + + if matching_pattern do return true + } + return false +} + +part_2 :: proc(lines: ^[]string) { + result: i64 = 0 + + for line in lines { + range := strings.split(line, "-") + lower, _ := strconv.parse_i64(range[0]) + upper, _ := strconv.parse_i64(range[1]) + + for id in lower ..= upper { + result += id if has_recurring_segments(id) else 0 + } + } + + fmt.printfln(" [Result] %v", result) +} + +main :: proc() { + context.allocator = context.temp_allocator + defer free_all(context.temp_allocator) + + INPUT :: #load("input.txt", string) + lines := strings.split(INPUT, ",") + + fmt.println("[Part 1]") + start := time.tick_now() + part_1(&lines) + duration := time.tick_diff(start, time.tick_now()) + fmt.printfln(" [Time] %vns\n", time.duration_nanoseconds(duration)) + + fmt.printfln("[Part 2]") + start = time.tick_now() + part_2(&lines) + duration = time.tick_diff(start, time.tick_now()) + fmt.printfln(" [Time] %vns", time.duration_nanoseconds(duration)) +}