From 5d32d932cc4e3c22c5b94f74269343b445023472 Mon Sep 17 00:00:00 2001 From: Adrian Perez de Castro Date: Sun, 21 Jan 2024 01:35:15 +0200 Subject: [PATCH] Day 01, Odin solution --- day01/day01.odin | 85 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 day01/day01.odin diff --git a/day01/day01.odin b/day01/day01.odin new file mode 100644 index 0000000..76bde9a --- /dev/null +++ b/day01/day01.odin @@ -0,0 +1,85 @@ +package main + +import "core:fmt" +import "core:os" +import "core:bufio" +import "core:slice" +import "core:unicode" + +process_line_a :: proc(line: []u8) -> int +{ + l, r: int + + for c in line { + if unicode.is_number(cast(rune) c) { + l = cast(int)c - '0' + break + } + } + #reverse for c in line { + if unicode.is_number(cast(rune) c) { + r = cast(int)c - '0' + break + } + } + + return l * 10 + r +} + +text_to_number :: proc(line: []u8, index: int) -> int +{ + number_names :: [] string { + "zero", "one", "two", "three", "four", + "five", "six", "seven", "eight", "nine", + } + for num, value in number_names { + tlen := len(num) + irem := line[index:] + if len(irem) >= tlen && string(irem[:tlen]) == num do return value + } + return -1 +} + +process_line_b :: proc(line: []u8) -> int +{ + l, r: int + + for i := 0; i < slice.length(line); i += 1 { + if unicode.is_number(cast(rune) line[i]) { + l = cast(int) line[i] - '0' + break + } + l = text_to_number(line, i) + if l >= 0 do break + } + + for i := slice.length(line) - 1; i >= 0; i -= 1 { + if unicode.is_number(cast(rune) line[i]) { + r = cast(int) line[i] - '0' + break + } + r = text_to_number(line, i) + if r >= 0 do break + } + + return 10 * l + r +} + +main :: proc() +{ + reader: bufio.Reader + bufio.reader_init(&reader, os.stream_from_handle(os.stdin)) + defer bufio.reader_destroy(&reader) + + sum_a, sum_b: int = 0, 0 + for { + line, err := bufio.reader_read_slice(&reader, '\n') + if err != nil do break + + sum_a += process_line_a(line) + sum_b += process_line_b(line) + } + + fmt.println("Sum A:", sum_a) + fmt.println("Sum B:", sum_b) +} -- 2.45.2