2019 Day 04 Done
This commit is contained in:
60
2019/day04/main.go
Normal file
60
2019/day04/main.go
Normal file
@@ -0,0 +1,60 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user