Compare commits
2 Commits
8d69f10924
...
a0ce63e5a5
| Author | SHA1 | Date | |
|---|---|---|---|
| a0ce63e5a5 | |||
| a12c8df252 |
46
internal/2015/DayFour/code.go
Normal file
46
internal/2015/DayFour/code.go
Normal 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)
|
||||
}
|
||||
45
internal/2015/DayFour/code_test.go
Normal file
45
internal/2015/DayFour/code_test.go
Normal 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user