Browse Source

Day 4 Python1

master
boB Rudis 3 years ago
parent
commit
78a70a5156
No known key found for this signature in database GPG Key ID: 1D7529BE14E2BBA9
  1. 282
      R/.Rhistory
  2. 1
      R/04.R
  3. 41
      R/04.py

282
R/.Rhistory

@ -1,144 +1,3 @@
return(
suppressWarnings(
switch(
field,
"byr" = stri_detect_regex(value, "^[[:digit:]]{4}$") & between(as.integer(value), 1920, 2002),
"iyr" = stri_detect_regex(value, "^[[:digit:]]{4}$") & between(as.integer(value), 2010, 2020),
"eyr" = stri_detect_regex(value, "^[[:digit:]]{4}$") & between(as.integer(value), 2020, 2030),
# "hgt" = stri_detect_regex(value, "^[[:digit:]]{2,3}(cm|in)$") & validate_height(value),
"hcl" = stri_detect_regex(value, "^#[a-f[:digit:]]{6}$"),
"ecl" = value %in% c("amb", "blu", "brn", "gry", "grn", "hzl", "oth"),
"pid" = stri_detect_regex(value, "^[[:digit:]]{9}$"),
"cid" = TRUE,
TRUE
)
}
split(input, findInterval(1:length(input), which(input == ""))) %>%
map(~{
paste0(.x, collapse = " ") %>%
stri_match_all_regex("([[:alpha:]]{3}):([^ $]+)") %>%
pluck(1) %>%
.[,2:3] %>%
as.data.frame() %>%
set_names(c("field", "value")) %>%
filter(field != "cid") -> found
#
# if (!all(found$field %in% req_keys) & (nrow(found) == length(req_keys))) return(FALSE)
#
# found %>%
# mutate(
# valid = map2(field, value, validate)
# )
})
library(stringi)
library(tidyverse)
req_keys <- c("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid")
input <- readLines("/tmp/test.txt")
split(input, findInterval(1:length(input), which(input == ""))) %>%
map_lgl(~{
paste0(.x, collapse = " ") %>%
stri_match_all_regex("([[:alpha:]]{3}):([^ $]+)") %>%
pluck(1) %>%
.[,2] %>%
discard(`==`, 'cid') -> found
all(found %in% req_keys) & (length(found) == length(req_keys))
}) %>%
sum()
validate_height <- function(value) {
matches <- unlist(stri_match_first_regex(value, "^([[:digit:]]{2,3})(cm|in)$"))
print(str(matches))
return(TRUE)
return(
switch(
matches[2],
"cm" = between(as.integer(m[1]), 150, 193),
"in" = between(as.integer(m[1]), 59, 76),
FALSE
)
}
validate <- function(field, value) {
print("[%s] [%s]", field, value)
return(
suppressWarnings(
switch(
field,
"byr" = stri_detect_regex(value, "^[[:digit:]]{4}$") & between(as.integer(value), 1920, 2002),
"iyr" = stri_detect_regex(value, "^[[:digit:]]{4}$") & between(as.integer(value), 2010, 2020),
"eyr" = stri_detect_regex(value, "^[[:digit:]]{4}$") & between(as.integer(value), 2020, 2030),
# "hgt" = stri_detect_regex(value, "^[[:digit:]]{2,3}(cm|in)$") & validate_height(value),
"hcl" = stri_detect_regex(value, "^#[a-f[:digit:]]{6}$"),
"ecl" = value %in% c("amb", "blu", "brn", "gry", "grn", "hzl", "oth"),
"pid" = stri_detect_regex(value, "^[[:digit:]]{9}$"),
"cid" = TRUE,
TRUE
)
}
split(input, findInterval(1:length(input), which(input == ""))) %>%
map(~{
paste0(.x, collapse = " ") %>%
stri_match_all_regex("([[:alpha:]]{3}):([^ $]+)") %>%
pluck(1) %>%
.[,2:3] %>%
as.data.frame() %>%
set_names(c("field", "value")) %>%
filter(field != "cid") -> found
#
# if (!all(found$field %in% req_keys) & (nrow(found) == length(req_keys))) return(FALSE)
#
# found %>%
# mutate(
# valid = map2(field, value, validate)
# )
})
split(input, findInterval(1:length(input), which(input == ""))) %>%
map(~{
paste0(.x, collapse = " ") %>%
stri_match_all_regex("([[:alpha:]]{3}):([^ $]+)") %>%
pluck(1) %>%
.[,2:3] %>%
as.data.frame() %>%
set_names(c("field", "value")) %>%
filter(field != "cid") -> found
#
# if (!all(found$field %in% req_keys) & (nrow(found) == length(req_keys))) return(FALSE)
#
found %>%
mutate(
valid = map2(field, value, validate)
)
})
validate <- function(field, value) {
print(str(field))
print(str(value))
return(
suppressWarnings(
switch(
field,
"byr" = stri_detect_regex(value, "^[[:digit:]]{4}$") & between(as.integer(value), 1920, 2002),
"iyr" = stri_detect_regex(value, "^[[:digit:]]{4}$") & between(as.integer(value), 2010, 2020),
"eyr" = stri_detect_regex(value, "^[[:digit:]]{4}$") & between(as.integer(value), 2020, 2030),
# "hgt" = stri_detect_regex(value, "^[[:digit:]]{2,3}(cm|in)$") & validate_height(value),
"hcl" = stri_detect_regex(value, "^#[a-f[:digit:]]{6}$"),
"ecl" = value %in% c("amb", "blu", "brn", "gry", "grn", "hzl", "oth"),
"pid" = stri_detect_regex(value, "^[[:digit:]]{9}$"),
"cid" = TRUE,
TRUE
)
}
split(input, findInterval(1:length(input), which(input == ""))) %>%
map(~{
paste0(.x, collapse = " ") %>%
stri_match_all_regex("([[:alpha:]]{3}):([^ $]+)") %>%
pluck(1) %>%
.[,2:3] %>%
as.data.frame() %>%
set_names(c("field", "value")) %>%
filter(field != "cid") -> found
#
# if (!all(found$field %in% req_keys) & (nrow(found) == length(req_keys))) return(FALSE)
#
found %>%
mutate(
valid = map2(field, value, validate)
)
})
@ -510,3 +369,144 @@ all(map2_lgl(found$field, found$value, validate))
}) %>%
sum()
reticulate::repl_python()
# --- Day 4: Passport Processing ---
#
# You arrive at the airport only to realize that you grabbed your North Pole Credentials instead of your passport. While these documents are extremely similar, North Pole Credentials aren't issued by a country and therefore aren't actually valid documentation for travel in most of the world.
#
# It seems like you're not the only one having problems, though; a very long line has formed for the automatic passport scanners, and the delay could upset your travel itinerary.
#
# Due to some questionable network security, you realize you might be able to solve both of these problems at the same time.
#
# The automatic passport scanners are slow because they're having trouble detecting which passports have all required fields. The expected fields are as follows:
#
# byr (Birth Year)
# iyr (Issue Year)
# eyr (Expiration Year)
# hgt (Height)
# hcl (Hair Color)
# ecl (Eye Color)
# pid (Passport ID)
# cid (Country ID)
#
# Passport data is validated in batch files (your puzzle input). Each passport
# is represented as a sequence of key:value pairs separated by spaces or newlines.
# Passports are separated by blank lines.
#
# Here is an example batch file containing four passports:
#
# ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
# byr:1937 iyr:2017 cid:147 hgt:183cm
#
# iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884
# hcl:#cfa07d byr:1929
#
# hcl:#ae17e1 iyr:2013
# eyr:2024
# ecl:brn pid:760753108 byr:1931
# hgt:179cm
#
# hcl:#cfa07d eyr:2025 pid:166559648
# iyr:2011 ecl:brn hgt:59in
#
# The first passport is valid - all eight fields are present. The second
# passport is invalid - it is missing hgt (the Height field).
#
# The third passport is interesting; the only missing field is cid, so it
# looks like data from North Pole Credentials, not a passport at all! Surely,
# nobody would mind if you made the system temporarily ignore missing cid
# fields. Treat this "passport" as valid.
#
# The fourth passport is missing two fields, cid and byr. Missing cid is
# fine, but missing any other field is not, so this passport is invalid.
#
# According to the above rules, your improved system would report 2 valid
# passports.
#
# Count the number of valid passports - those that have all required fields.
# Treat cid as optional. In your batch file, how many passports are valid?
library(stringi)
library(tidyverse)
req_keys <- c("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid")
input <- readLines("../input/04-01.txt")
# 04-01 -------------------------------------------------------------------
split(input, findInterval(1:length(input), which(input == ""))) %>%
map_lgl(~{
paste0(.x, collapse = " ") %>%
stri_match_all_regex("([[:alpha:]]{3}):([^ $]+)") %>%
pluck(1) %>%
.[,2] %>%
discard(`==`, 'cid') -> found
all(found %in% req_keys) & (length(found) == length(req_keys))
}) %>%
sum()
# --- Day 4: Passport Processing ---
#
# You arrive at the airport only to realize that you grabbed your North Pole Credentials instead of your passport. While these documents are extremely similar, North Pole Credentials aren't issued by a country and therefore aren't actually valid documentation for travel in most of the world.
#
# It seems like you're not the only one having problems, though; a very long line has formed for the automatic passport scanners, and the delay could upset your travel itinerary.
#
# Due to some questionable network security, you realize you might be able to solve both of these problems at the same time.
#
# The automatic passport scanners are slow because they're having trouble detecting which passports have all required fields. The expected fields are as follows:
#
# byr (Birth Year)
# iyr (Issue Year)
# eyr (Expiration Year)
# hgt (Height)
# hcl (Hair Color)
# ecl (Eye Color)
# pid (Passport ID)
# cid (Country ID)
#
# Passport data is validated in batch files (your puzzle input). Each passport
# is represented as a sequence of key:value pairs separated by spaces or newlines.
# Passports are separated by blank lines.
#
# Here is an example batch file containing four passports:
#
# ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
# byr:1937 iyr:2017 cid:147 hgt:183cm
#
# iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884
# hcl:#cfa07d byr:1929
#
# hcl:#ae17e1 iyr:2013
# eyr:2024
# ecl:brn pid:760753108 byr:1931
# hgt:179cm
#
# hcl:#cfa07d eyr:2025 pid:166559648
# iyr:2011 ecl:brn hgt:59in
#
# The first passport is valid - all eight fields are present. The second
# passport is invalid - it is missing hgt (the Height field).
#
# The third passport is interesting; the only missing field is cid, so it
# looks like data from North Pole Credentials, not a passport at all! Surely,
# nobody would mind if you made the system temporarily ignore missing cid
# fields. Treat this "passport" as valid.
#
# The fourth passport is missing two fields, cid and byr. Missing cid is
# fine, but missing any other field is not, so this passport is invalid.
#
# According to the above rules, your improved system would report 2 valid
# passports.
#
# Count the number of valid passports - those that have all required fields.
# Treat cid as optional. In your batch file, how many passports are valid?
library(stringi)
library(tidyverse)
req_keys <- c("byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid")
input <- readLines("../input/04-01.txt")
# 04-01 -------------------------------------------------------------------
split(input, findInterval(1:length(input), which(input == ""))) %>%
map_lgl(~{
paste0(.x, collapse = " ") %>%
stri_match_all_regex("([[:alpha:]]{3}):([^ $]+)") %>%
pluck(1) %>%
.[,2] %>%
discard(`==`, 'cid') -> found
all(found %in% req_keys) & (length(found) == length(req_keys))
}) %>%
sum()
reticulate::repl_python()

1
R/04.R

@ -137,7 +137,6 @@ validate <- function(field, value) {
)
)
}
split(input, findInterval(1:length(input), which(input == ""))) %>%

41
R/04.py

@ -1,7 +1,6 @@
from itertools import groupby
import re
# with open("/tmp/test.txt") as f:
with open("../input/04-01.txt") as f:
input = f.read().splitlines()
@ -9,9 +8,49 @@ req_keys = set([ "byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid" ])
recs = [ ' '.join(list(grp)) for key, grp in groupby(input, lambda str: str != "") if key ]
# 04-01 -------------------------------------------------------------------
def test_fields(rec):
fields = set(re.findall("([a-z]{3}):", rec))
return(len(req_keys.difference(fields)) == 0)
sum([ test_fields(rec) for rec in recs ])
# 04-02 -------------------------------------------------------------------
def validate_height(value):
match = re.match(r"^(?P<val>[0-9]{2,3})(?P<unit>cm|in)$"
val = int(match.group("val"))
unit = match.group("unit")
if (unit == "cm"):
return(150 <= val <= 193)
else:
return(59 <= val <= 76)
def validate(fval):
return({
"byr": lambda x: re.match(r"^[0-9]{4}$", fval[1]) && (1920 <=int(fval[1]) <= 2002),
"iyr": lambda x: re.match(r"^[0-9]{4}$", fval[1]) && (2010 <=int(fval[1]) <= 2020),
"eyr": lambda x: re.match(r"^[0-9]{4}$", fval[1]) && (2020 <=int(fval[1]) <= 2030),
"hgt": lambda x: re.match(r"^[0-9]{2,3}(cm|in)$", fval[1]) && validate_height(fval[1]),
"hcl": lambda x: re.match(r"#[a-f0-9]{6}", fval[1]),
"ecl": lambda x: fval[1] in set(["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]),
"hcl": lambda x: re.match(r"[0-9]{9}^$", fval[1])
}[fval[0]](fval[1]))
def validate_fields(rec):
fvals = re.findall("([a-z]{3}):([^ $]+)", rec)
fields = set([ x[0] for x in fvals ])
if (len(req_keys.difference(fields)) != 0):
return(False)
fvals = list(filter(lambda y: y[0] != 'cid', fvals))
res = sum([ validate(x) for x in fvals ]) == 7
return(res)
sum([ validate_fields(rec) for rec in recs ])

Loading…
Cancel
Save