Skip to content

Commit

Permalink
D1: implement a solution for puzzle part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
benhsm committed Dec 1, 2022
0 parents commit 6366fd0
Show file tree
Hide file tree
Showing 5 changed files with 2,332 additions and 0 deletions.
38 changes: 38 additions & 0 deletions day_1/day_1_.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package main

import (
"bufio"
"fmt"
"io"
"log"
"os"
"strconv"
)

func main() {
inputFile, err := os.OpenFile("input", os.O_RDWR, 0666)
if err != nil {
log.Fatalf("error reading input data %v", err)
}
fmt.Printf("The elf with the most calories has %d calories", findMostCalories(inputFile))
}

func findMostCalories(input io.Reader) int {
r := bufio.NewScanner(input)
var maxSeen, calories int
for r.Scan() {
if r.Text() == "" {
if calories > maxSeen {
maxSeen = calories
}
calories = 0
} else {
toAdd, err := strconv.Atoi(r.Text())
if err != nil {
log.Fatalf("could not interpret data as calories: %v", err)
}
calories += toAdd
}
}
return maxSeen
}
29 changes: 29 additions & 0 deletions day_1/day_1_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package main

import (
"strings"
"testing"
)

func TestFindMostCalories(t *testing.T) {
t.Run("basic case", func(t *testing.T) {
input := strings.NewReader(`1000
2000
3000
4000
5000
6000
7000
8000
9000
10000`)
answer := findMostCalories(input)
if answer != 24000 {
t.Errorf("want answer 24000, got %v", answer)
}
})
}
3 changes: 3 additions & 0 deletions day_1/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module aoc_day_1

go 1.19
Loading

0 comments on commit 6366fd0

Please sign in to comment.