From 6af666ac392c6b26aa42f7e8e4dde630f351b2d4 Mon Sep 17 00:00:00 2001 From: alexchao26 Date: Mon, 21 Dec 2020 22:39:08 -0500 Subject: [PATCH] 2016-day05: md5 hashing, slowww --- 2016/day05/main.go | 55 +++++++++++++++++++++++++++++++++++++++++ 2016/day05/main_test.go | 28 +++++++++++++++++++++ 2 files changed, 83 insertions(+) create mode 100644 2016/day05/main.go create mode 100644 2016/day05/main_test.go diff --git a/2016/day05/main.go b/2016/day05/main.go new file mode 100644 index 0000000..2e2a235 --- /dev/null +++ b/2016/day05/main.go @@ -0,0 +1,55 @@ +package main + +import ( + "crypto/md5" + "flag" + "fmt" + "regexp" + "strings" + + "github.com/alexchao26/advent-of-code-go/cast" + "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 := md5Chess(util.ReadFile("./input.txt"), part) + util.CopyToClipboard(fmt.Sprintf("%v", ans)) + fmt.Println("Output:", ans) +} + +func md5Chess(input string, part int) string { + passwordParts := map[int]string{} + var part1Index int + + for i := 0; len(passwordParts) < 8; i++ { + in := fmt.Sprintf("%s%d", input, i) + hash := fmt.Sprintf("%x", md5.Sum([]byte(in))) + + if strings.HasPrefix(hash, "00000") { + if part == 1 { + passwordParts[part1Index] = hash[5:6] + part1Index++ + } else { + if regexp.MustCompile("[0-7]").MatchString(hash[5:6]) { + index := cast.ToInt(hash[5:6]) + if _, ok := passwordParts[index]; !ok { + value := hash[6:7] + passwordParts[index] = value + } + } + } + } + } + + var password string + for i := 0; i < 8; i++ { + password += passwordParts[i] + } + + return password +} diff --git a/2016/day05/main_test.go b/2016/day05/main_test.go new file mode 100644 index 0000000..0f34f1b --- /dev/null +++ b/2016/day05/main_test.go @@ -0,0 +1,28 @@ +package main + +import ( + "testing" + + "github.com/alexchao26/advent-of-code-go/util" +) + +func Test_md5Chess(t *testing.T) { + tests := []struct { + name string + input string + part int + want string + }{ + {"example_part1", "abc", 1, "18f47a30"}, + {"actual_part1", util.ReadFile("input.txt"), 1, "801b56a7"}, + {"example_part2", "abc", 2, "05ace8e3"}, + {"actual_part2", "abc", 2, "424a0197"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := md5Chess(tt.input, tt.part); got != tt.want { + t.Errorf("md5Chess() = %v, want %v", got, tt.want) + } + }) + } +}