-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
D1: implement a solution for puzzle part 1
- Loading branch information
0 parents
commit 6366fd0
Showing
5 changed files
with
2,332 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
module aoc_day_1 | ||
|
||
go 1.19 |
Oops, something went wrong.