adventofcode/2019/day04/main.go

61 lines
959 B
Go
Raw Normal View History

2019-12-04 14:40:52 +00:00
package main
import (
"bytes"
"fmt"
"os"
)
func main() {
beg, end := []byte("165432"), []byte("707912")
if len(os.Args) == 3 {
beg, end = []byte(os.Args[1]), []byte(os.Args[2])
}
var count int
for {
if validate(beg) {
count++
}
if bytes.Equal(beg, end) {
break
}
beg = inc(beg)
}
fmt.Println(count)
}
func inc(num []byte) []byte {
if len(num) == 0 {
return []byte{'1'}
} else if num[len(num)-1] == '9' {
return append(inc(num[:len(num)-1]), '0')
} else {
num[len(num)-1]++
}
return num
}
func validate(num []byte) bool {
var dup bool
for k := range num {
if countSeq(num, k) == 2 {
dup = true
}
if len(num) > k+1 && num[k] > num[k+1] {
return false
}
}
return dup
}
func countSeq(num []byte, idx int) int {
ret := 1
if len(num) > idx+1 && num[idx+1] == num[idx] {
ret += countSeq(num[idx+1:], 0)
}
if idx >= 1 && num[idx-1] == num[idx] {
ret += countSeq(num[:idx], idx-1)
}
return ret
}