2015-day4: md5 hashing

This commit is contained in:
alexchao26
2020-12-26 02:08:25 -05:00
parent 33fb66a61e
commit 705884d080
2 changed files with 64 additions and 0 deletions
+38
View File
@@ -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")
}
+26
View File
@@ -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)
}
})
}
}