Skip to content

Instantly share code, notes, and snippets.

@hovsater
Last active July 19, 2023 15:14
Show Gist options
  • Save hovsater/478585a19e7fb4cb54bf8988ec874925 to your computer and use it in GitHub Desktop.
Save hovsater/478585a19e7fb4cb54bf8988ec874925 to your computer and use it in GitHub Desktop.
Solution to part 1 of Advent of Code 2018 (See https://adventofcode.com/2018/day/1)
package main
import "core:io"
import "core:strings"
import "core:testing"
freq :: proc(stream: io.Stream) -> (res: int) {
base :: 10
sign := 1
num: int
for {
b, err := io.read_byte(stream)
if err == .EOF do break
if err != nil do panic("unexpected error")
switch b {
case '+':
sign = +1
case '-':
sign = -1
case ',':
res += num * sign
num = 0
case ' ':
continue
case:
num = num * base + int(b - '0')
}
}
if num > 0 {
res += num * sign
}
return
}
@(test)
test_part1 :: proc(t: ^testing.T) {
reader: strings.Reader
strings.reader_init(&reader, "+1, +1, +1")
testing.expect_value(t, freq(strings.reader_to_stream(&reader)), 3)
strings.reader_init(&reader, "+1, +1, -2")
testing.expect_value(t, freq(strings.reader_to_stream(&reader)), 0)
strings.reader_init(&reader, "-1, -2, -3")
testing.expect_value(t, freq(strings.reader_to_stream(&reader)), -6)
strings.reader_init(&reader, "+10, -15, +20")
testing.expect_value(t, freq(strings.reader_to_stream(&reader)), 15)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment