2019/day4/main.go
2019-12-04 22:23:59 +01:00

109 lines
1.6 KiB
Go

package main
import (
"log"
"math"
"strconv"
)
func main() {
countPasswords := CountPossiblePasswords(245318, 765747, false)
countAdditionalPasswords := CountPossiblePasswords(245318, 765747, true)
log.Println("Part1: " + strconv.Itoa(countPasswords))
log.Println("Part2: " + strconv.Itoa(countAdditionalPasswords))
}
func CountPossiblePasswords(start int, end int, additional bool) int {
sum := 0
for i := start; i < end; i++ {
if MeetPasswordCriteria(i, additional) {
sum++
}
}
return sum
}
func MeetPasswordCriteria(number int, additional bool) bool {
if CountDigits(number) != 6 {
return false
}
if !AreDigitsNotDecreasing(number) {
return false
}
if !HaveDoubleInputs(number) {
return false
}
if additional && !HasOneDouble(number) {
return false
}
return true
}
func CountDigits(i int) int {
count := 0
for i != 0 {
i /= 10
count = count + 1
}
return count
}
func AreDigitsNotDecreasing(i int) bool {
iStr := strconv.Itoa(i)
prevInt := math.MinInt32
for _, a := range iStr {
aInt, _ := strconv.Atoi(string(a))
if prevInt > aInt {
return false
}
prevInt = aInt
}
return true
}
func HaveDoubleInputs(i int) bool {
iStr := strconv.Itoa(i)
hasDouble := false
for i := 0; i < len(iStr)-1; i++ {
if iStr[i] == iStr[i+1] {
hasDouble = true
}
}
return hasDouble
}
func HasOneDouble(i int) bool {
iStr := strconv.Itoa(i)
for len(iStr) >= 2 {
if iStr[0] != iStr[1] {
iStr = iStr[1:]
continue
}
i := 1
for len(iStr) > i && iStr[0] == iStr[i] {
i++
}
if i == 2 {
return true
}
if len(iStr) <= i {
return false
}
iStr = iStr[i:]
}
return false
}