Alexander Avery
12 months ago
3 changed files with 1136 additions and 0 deletions
@ -0,0 +1,68 @@ |
|||
package main |
|||
|
|||
import ( |
|||
"bufio" |
|||
"fmt" |
|||
"io" |
|||
"strconv" |
|||
"unicode" |
|||
) |
|||
|
|||
type day01 struct { |
|||
} |
|||
|
|||
type buffer struct { |
|||
first bool |
|||
d1 rune |
|||
|
|||
last bool |
|||
d2 rune |
|||
} |
|||
|
|||
func (b *buffer) value() (value uint64) { |
|||
var d2 rune |
|||
|
|||
if b.last { |
|||
d2 = b.d2 |
|||
} else { |
|||
d2 = b.d1 |
|||
} |
|||
|
|||
str := fmt.Sprintf("%c%c", b.d1, d2) |
|||
value, _ = strconv.ParseUint(str, 10, 64) |
|||
|
|||
b.first, b.last = false, false |
|||
return |
|||
} |
|||
|
|||
func (b *buffer) record(digit rune) { |
|||
if !b.first { |
|||
b.d1 = digit |
|||
b.first = true |
|||
} else { |
|||
b.d2 = digit |
|||
b.last = true |
|||
} |
|||
} |
|||
|
|||
func (d day01) solve(r io.Reader) string { |
|||
var ( |
|||
buffer buffer |
|||
total uint64 |
|||
buf = bufio.NewReader(r) |
|||
) |
|||
|
|||
for { |
|||
b, _, err := buf.ReadRune() |
|||
if err != nil { |
|||
return fmt.Sprintf("%d", total+buffer.value()) |
|||
} |
|||
|
|||
if unicode.IsDigit(b) { |
|||
buffer.record(b) |
|||
} else if b == '\n' { |
|||
total += buffer.value() |
|||
} |
|||
|
|||
} |
|||
} |
File diff suppressed because it is too large
@ -0,0 +1,68 @@ |
|||
package main |
|||
|
|||
import ( |
|||
"flag" |
|||
"fmt" |
|||
"io" |
|||
"log" |
|||
"os" |
|||
"path/filepath" |
|||
"strconv" |
|||
) |
|||
|
|||
type puzzle interface { |
|||
solve(r io.Reader) string |
|||
} |
|||
|
|||
var ( |
|||
// pick which day to run with a flag
|
|||
day = flag.String("d", "", "which day to solve") |
|||
|
|||
// slice of all puzzles
|
|||
puzzles = []puzzle{ |
|||
&day01{}, |
|||
} |
|||
) |
|||
|
|||
func init() { |
|||
flag.Parse() |
|||
|
|||
} |
|||
|
|||
func inputs(day int64) []io.Reader { |
|||
inputs := make([]io.Reader, 0, 2) |
|||
path := fmt.Sprintf("input/%d-[1-2]", day) |
|||
|
|||
matches, err := filepath.Glob(path) |
|||
if err != nil { |
|||
log.Fatalf("matching puzzle input files: %s", err.Error()) |
|||
} |
|||
|
|||
fmt.Println(matches) |
|||
|
|||
for _, match := range matches { |
|||
f, err := os.Open(match) |
|||
if err == nil { |
|||
inputs = append(inputs, f) |
|||
} |
|||
} |
|||
|
|||
return inputs |
|||
} |
|||
|
|||
func main() { |
|||
puzzleIndex, err := strconv.ParseInt(*day, 10, 32) |
|||
if err != nil { |
|||
log.Fatalf("invalid puzzle day: %s", *day) |
|||
} |
|||
inputs := inputs(puzzleIndex) |
|||
|
|||
puzzle := puzzles[puzzleIndex-1] |
|||
|
|||
fmt.Fprintf(os.Stdout, "Day %d:\n", puzzleIndex) |
|||
for i := range inputs { |
|||
ans := puzzle.solve(inputs[i]) |
|||
fmt.Fprintf(os.Stdout, "Solution %d:\n%s", i+1, ans) |
|||
} |
|||
fmt.Fprintln(os.Stdout) |
|||
} |
Loading…
Reference in new issue