You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
99 lines
2.0 KiB
99 lines
2.0 KiB
package main |
|
|
|
import ( |
|
"../helper" |
|
"fmt" |
|
"os" |
|
"regexp" |
|
"strconv" |
|
"strings" |
|
) |
|
|
|
func main() { |
|
args := os.Args[1:] |
|
input, err := helper.GetFile(args[0]) |
|
if err != nil { |
|
fmt.Println(err) |
|
} |
|
reqFields := []string{"byr:", "iyr:", "eyr:", "hgt:", "hcl:", "ecl:", "pid:"} |
|
documents := strings.Split(input, "\n\n") |
|
count := 0 |
|
countPart2 := 0 |
|
for _, document := range documents { |
|
if isValid(document, reqFields) { |
|
count++ |
|
if isValidPart2(document) { |
|
countPart2++ |
|
} |
|
} |
|
} |
|
fmt.Println(count) |
|
fmt.Println(countPart2) |
|
} |
|
|
|
func isValid(document string, reqFields []string) bool { |
|
for _, reqField := range reqFields { |
|
match, err := regexp.MatchString(reqField, document) |
|
if err != nil { |
|
fmt.Println(err) |
|
} |
|
if !match { |
|
return false |
|
} |
|
} |
|
return true |
|
} |
|
|
|
func isValidPart2(document string) bool { |
|
fields := strings.Fields(document) |
|
for i := 0; i < len(fields); i++ { |
|
field := fields[i] |
|
pair := strings.Split(field, ":") |
|
switch pair[0] { |
|
case "byr": |
|
if !checkYear(pair[1], 2002, 1920) { |
|
return false |
|
} |
|
case "iyr": |
|
if !checkYear(pair[1], 2020, 2010) { |
|
return false |
|
} |
|
case "eyr": |
|
if !checkYear(pair[1], 2030, 2020) { |
|
return false |
|
} |
|
case "hgt": |
|
r, _ := regexp.Compile("(cm|in)") |
|
switch r.FindString(pair[1]) { |
|
case "cm": |
|
if !checkYear(pair[1][:len(pair[1])-2], 193, 150) { |
|
return false |
|
} |
|
case "in": |
|
if !checkYear(pair[1][:len(pair[1])-2], 76, 59) { |
|
return false |
|
} |
|
default: |
|
return false |
|
} |
|
case "hcl": |
|
if match, _ := regexp.MatchString("^#[a-f0-9]{6}", pair[1]); !match{ |
|
return false |
|
} |
|
case "ecl": |
|
if match, _ := regexp.MatchString(pair[1], "amb blue brn gry grn hzl oth"); !match{ |
|
return false |
|
} |
|
case "pid": |
|
if match, _ := regexp.MatchString("[0-9]{8}", pair[1]); !match{ |
|
return false |
|
} |
|
} |
|
} |
|
return true |
|
} |
|
|
|
func checkYear(year string, max int, min int) bool { |
|
number, err := strconv.Atoi(year) |
|
return err == nil && number >= min && number <= max |
|
}
|
|
|