mirror of
https://github.com/Threnklyn/advent-of-code-go.git
synced 2026-06-07 04:33:31 +02:00
2015-day4: md5 hashing
This commit is contained in:
@@ -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")
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user