Compare commits

...

2 Commits

Author SHA1 Message Date
a0ce63e5a5 feat: solve d4 both parts using md5 bruteforce 2025-11-29 09:57:54 +01:00
a12c8df252 test: add unit tests for both parts 2025-11-29 09:57:23 +01:00
2 changed files with 91 additions and 0 deletions

View File

@@ -0,0 +1,46 @@
package dayfour
import (
"advent-of-code/internal/registry"
"bytes"
"crypto/md5"
"os"
"strconv"
)
func init() {
registry.Register("2015D4", ParseInput, PartOne, PartTwo)
}
func ParseInput(filepath string) []byte {
content, _ := os.ReadFile(filepath)
return bytes.TrimSpace(content)
}
func findHashWithZeroes(data []byte, zeroes int) int {
buffer := make([]byte, len(data), len(data)+10)
copy(buffer, data)
for idx := 1; ; idx++ {
buffer = buffer[:len(data)]
buffer = strconv.AppendInt(buffer, int64(idx), 10)
hash := md5.Sum(buffer)
switch zeroes {
case 5:
if hash[0] == 0 && hash[1] == 0 && hash[2]&0xF0 == 0 {
return idx
}
case 6:
if hash[0] == 0 && hash[1] == 0 && hash[2] == 0 {
return idx
}
}
}
}
func PartOne(data []byte) int {
return findHashWithZeroes(data, 5)
}
func PartTwo(data []byte) int {
return findHashWithZeroes(data, 6)
}

View File

@@ -0,0 +1,45 @@
package dayfour
import (
"testing"
)
func TestPartOne(t *testing.T) {
tests := []struct {
name string
input []byte
expected int
}{
{"abcdef", []byte("abcdef"), 609043},
{"pqrstuv", []byte("pqrstuv"), 1048970},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := PartOne(tt.input)
if got != tt.expected {
t.Errorf("PartOne() = %d, want %d", got, tt.expected)
}
})
}
}
func TestPartTwo(t *testing.T) {
tests := []struct {
name string
input []byte
expected int
}{
{"abcdef", []byte("abcdef"), 6742839},
{"pqrstuv", []byte("pqrstuv"), 5714438},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := PartTwo(tt.input)
if got != tt.expected {
t.Errorf("PartTwo() = %d, want %d", got, tt.expected)
}
})
}
}