From 705884d0807efeb4566cdde61d2aa5afb5435f51 Mon Sep 17 00:00:00 2001 From: alexchao26 Date: Sat, 26 Dec 2020 02:08:25 -0500 Subject: [PATCH] 2015-day4: md5 hashing --- 2015/day04/main.go | 38 ++++++++++++++++++++++++++++++++++++++ 2015/day04/main_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 2015/day04/main.go create mode 100644 2015/day04/main_test.go diff --git a/2015/day04/main.go b/2015/day04/main.go new file mode 100644 index 0000000..4aef2c7 --- /dev/null +++ b/2015/day04/main.go @@ -0,0 +1,38 @@ +package main + +import ( + "crypto/md5" + "flag" + "fmt" + "math" + "strings" + + "github.com/alexchao26/advent-of-code-go/util" +) + +func main() { + var part int + flag.IntVar(&part, "part", 1, "part 1 or 2") + flag.Parse() + fmt.Println("Running part", part) + + ans := md5StockingStuffer(util.ReadFile("./input.txt"), part) + fmt.Println("Output:", ans) +} + +func md5StockingStuffer(input string, part int) int { + prefixZeroes := 5 + if part == 2 { + prefixZeroes = 6 + } + + for i := 0; i < math.MaxInt32; i++ { + toHash := fmt.Sprintf("%s%d", input, i) + hashed := fmt.Sprintf("%x", md5.Sum([]byte(toHash))) + if strings.HasPrefix(hashed, strings.Repeat("0", prefixZeroes)) { + return i + } + } + + panic("no hash found") +} diff --git a/2015/day04/main_test.go b/2015/day04/main_test.go new file mode 100644 index 0000000..8baa1cc --- /dev/null +++ b/2015/day04/main_test.go @@ -0,0 +1,26 @@ +package main + +import ( + "testing" + + "github.com/alexchao26/advent-of-code-go/util" +) + +func Test_md5StockingStuffer(t *testing.T) { + tests := []struct { + name string + input string + part int + want int + }{ + {"part1 actual", util.ReadFile("input.txt"), 1, 254575}, + {"part2 actual", util.ReadFile("input.txt"), 2, 1038736}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := md5StockingStuffer(tt.input, tt.part); got != tt.want { + t.Errorf("md5StockingStuffer() = %v, want %v", got, tt.want) + } + }) + } +}