DEV Community

Cover image for Advent of Code 2020 Solution Megathread - Day 4: Passport Processing
Ryan Palo
Ryan Palo

Posted on • Edited on

Advent of Code 2020 Solution Megathread - Day 4: Passport Processing

Day 4! I was worried as I was reading the first problem yesterday that I would have to optimize for any rational slope. I'm thankful he decided to take it easier than that for Day 3.

The Puzzle

In today’s puzzle, we're just trying to get through airport security, which is jam-packed because, obviously, Santa's magic keeps the North Pole COVID-free. It's classified as a hum-bug. 🥁 Anyways. The passport scanner is broken and we're doing a good deed by "fixing" it. And by "fixing," we mean "hacking it to let us through but also mostly fixing it."

Y'all. We are THIS close to validating YAML and I am here for it.

The Leaderboards

As always, this is the spot where I’ll plug any leaderboard codes shared from the community.

Ryan's Leaderboard: 224198-25048a19
Enter fullscreen mode Exit fullscreen mode

If you want to generate your own leaderboard and signal boost it a little bit, send it to me either in a DEV message or in a comment on one of these posts and I'll add it to the list above.

Yesterday’s Languages

Updated 03:06PM 12/12/2020 PST.

Language Count
Python 8
JavaScript 3
Rust 2
Haskell 2
C# 1
Raku 1
COBOL 1
PHP 1
Ruby 1
Elixir 1
Go 1
C 1

Merry Coding!

Oldest comments (23)

Collapse
 
benwtrent profile image
Benjamin Trent

My super gross rust impl. Messy regex. I am sure there are way better ways to parse according to white space.

Also, I sort of went half-way with a struct solution. Probably would have been better to either go all the way or not have custom types at all.

#[derive(Debug)]
struct Passport {
    birth_year: Option<usize>,
    issue_year: Option<usize>,
    exp_year: Option<usize>,
    height: Option<String>,
    hair_color: Option<String>,
    eye_color: Option<String>,
    pid: Option<String>,
    cid: Option<usize>,
}

impl From<&str> for Passport {
    fn from(s: &str) -> Self {
        let (
            mut birth_year,
            mut issue_year,
            mut exp_year,
            mut height,
            mut hair_color,
            mut eye_color,
            mut pid,
            mut cid,
        ) = (
            Option::None,
            Option::None,
            Option::None,
            Option::None,
            Option::None,
            Option::None,
            Option::None,
            Option::None,
        );
        s.split(" ").filter(|i| !i.is_empty()).for_each(|i| {
            let name_var: Vec<&str> = i.split(":").collect();
            match name_var[0] {
                "byr" => birth_year = Option::Some(name_var[1].parse().unwrap()),
                "iyr" => issue_year = Option::Some(name_var[1].parse().unwrap()),
                "eyr" => exp_year = Option::Some(name_var[1].parse().unwrap()),
                "hgt" => height = Option::Some(String::from(name_var[1])),
                "hcl" => hair_color = Option::Some(String::from(name_var[1])),
                "ecl" => eye_color = Option::Some(String::from(name_var[1])),
                "pid" => pid = Option::Some(String::from(name_var[1])),
                "cid" => cid = Option::Some(name_var[1].parse().unwrap()),
                _ => {}
            }
        });
        Passport {
            birth_year,
            issue_year,
            exp_year,
            height,
            hair_color,
            eye_color,
            pid,
            cid,
        }
    }
}

impl Passport {
    pub fn is_valid(&self) -> bool {
        self.birth_year.is_some()
            && self.issue_year.is_some()
            && self.exp_year.is_some()
            && self.height.is_some()
            && self.hair_color.is_some()
            && self.eye_color.is_some()
            && self.pid.is_some()
    }

    pub fn is_valid_strict(&self) -> bool {
        self.valid_birth_year()
            && self.valid_issue_year()
            && self.valid_exp_year()
            && self.valid_hgt()
            && self.valid_hair()
            && self.valid_eyes()
            && self.valid_pid()
    }

    fn valid_birth_year(&self) -> bool {
        (1920..=2002).contains(&self.birth_year.unwrap_or_default())
    }

    fn valid_issue_year(&self) -> bool {
        (2010..=2020).contains(&self.issue_year.unwrap_or_default())
    }

    fn valid_exp_year(&self) -> bool {
        (2020..=2030).contains(&self.exp_year.unwrap_or_default())
    }

    fn valid_hgt(&self) -> bool {
        if let Some(height) = self.height.as_ref() {
            let range = match &height[height.len() - 2..] {
                "in" => (59..=76),
                "cm" => (150..=193),
                _ => return false,
            };
            range.contains(&height[0..height.len() - 2].parse::<usize>().unwrap_or(0))
        } else {
            false
        }
    }

    fn valid_hair(&self) -> bool {
        Passport::valid_str(self.hair_color.as_ref(), r"^#[0-9a-f]{6}$")
    }

    fn valid_eyes(&self) -> bool {
        Passport::valid_str(self.eye_color.as_ref(), r"^amb|blu|brn|gry|grn|hzl|oth$")
    }

    fn valid_pid(&self) -> bool {
        Passport::valid_str(self.pid.as_ref(), r"^[0-9]{9}$")
    }

    fn valid_str(maybe_str: Option<&String>, re: &str) -> bool {
        if let Some(str) = maybe_str {
            let re = regex::Regex::new(re).unwrap();
            let captures = re.captures(str.as_str());
            captures.is_some()
        } else {
            false
        }
    }
}

#[aoc_generator(day4)]
fn input_to_vec(input: &str) -> Vec<Passport> {
    let mut cleaned_str = String::from("");
    let mut cleaned_input: Vec<Passport> = vec![];
    input.lines().for_each(|i| {
        if i.is_empty() && !cleaned_str.is_empty() {
            cleaned_input.push(Passport::from(cleaned_str.as_str()));
            cleaned_str = String::from("");
        }
        cleaned_str += i;
        cleaned_str += " ";
    });
    if !cleaned_str.is_empty() {
        cleaned_input.push(Passport::from(cleaned_str.as_str()));
    }
    cleaned_input
}

#[aoc(day4, part1)]
fn valid_count(input: &Vec<Passport>) -> usize {
    input.iter().filter(|p| p.is_valid()).count()
}

#[aoc(day4, part2)]
fn strict_valid_count(input: &Vec<Passport>) -> usize {
    input.iter().filter(|p| p.is_valid_strict()).count()
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ballpointcarrot profile image
Christopher Kruse

You're not alone in the ugly feeling. I had a particularly nasty bug that gave me one result too many in part two (realized I had a missing ^ and $ on the regex for pid).

I see a fair amount of similarities in approach, so I'm glad to see I'm in good company. :D

As always, on Github.

use aoc_runner_derive::{aoc, aoc_generator};
use regex::Regex;

#[derive(Debug, PartialEq)]
struct Height {
    measure: usize,
    unit: String,
}

impl Height {
    fn parse(hgt_str: &str) -> Option<Height> {
        let re = Regex::new("(\\d+)(in|cm)").expect("Unable to create Regex");
        match re.captures(hgt_str) {
            None => None,
            Some(captures) => {
                let h = Height {
                    measure: str::parse(captures.get(1).unwrap().as_str())
                        .expect("Unable to parse number"),
                    unit: String::from(captures.get(2).unwrap().as_str()),
                };
                Some(h)
            }
        }
    }
    fn is_valid(&self) -> bool {
        match self.unit.as_str() {
            "cm" => self.measure >= 150 && self.measure <= 193,
            "in" => self.measure >= 59 && self.measure <= 76,
            _ => panic!("Not a valid unit"),
        }
    }
}

#[derive(Debug, PartialEq)]
struct Passport {
    byr: Option<usize>,
    iyr: Option<usize>,
    eyr: Option<usize>,
    hgt: Option<Height>,
    hgt_str: Option<String>,
    hcl: Option<String>,
    ecl: Option<String>,
    pid: Option<String>,
    cid: Option<String>,
}

impl Passport {
    fn new() -> Passport {
        Passport {
            byr: None,
            iyr: None,
            eyr: None,
            hgt: None,
            hgt_str: None,
            hcl: None,
            ecl: None,
            pid: None,
            cid: None,
        }
    }

    fn has_fields(&self) -> bool {
        self.byr.is_some()
            && self.iyr.is_some()
            && self.eyr.is_some()
            && self.hgt_str.is_some()
            && self.hcl.is_some()
            && self.ecl.is_some()
            && self.pid.is_some()
    }

    fn is_valid(&self) -> bool {
        self.valid_byr()
            && self.valid_iyr()
            && self.valid_eyr()
            && self.valid_hgt()
            && self.valid_hcl()
            && self.valid_ecl()
            && self.valid_pid()
    }

    fn valid_byr(&self) -> bool {
        match self.byr {
            None => false,
            Some(n) => n >= 1920 && n <= 2002,
        }
    }
    fn valid_iyr(&self) -> bool {
        match self.iyr {
            None => false,
            Some(n) => n >= 2010 && n <= 2020,
        }
    }
    fn valid_eyr(&self) -> bool {
        match self.eyr {
            None => false,
            Some(n) => n >= 2020 && n <= 2030,
        }
    }
    fn valid_hgt(&self) -> bool {
        match &self.hgt {
            None => false,
            Some(h) => h.is_valid(),
        }
    }
    fn valid_hcl(&self) -> bool {
        let re = Regex::new("^#[0-9a-f]{6}$").expect("Failed to make regex");
        match &self.hcl {
            None => false,
            Some(hair) => re.is_match(hair.as_str()),
        }
    }
    fn valid_ecl(&self) -> bool {
        let valid_colors = vec!["amb", "blu", "brn", "gry", "grn", "hzl", "oth"];
        match &self.ecl {
            None => false,
            Some(c) => valid_colors.contains(&c.as_str()),
        }
    }
    fn valid_pid(&self) -> bool {
        let re = Regex::new("^[0-9]{9}$").expect("Failed to build Regex");
        match &self.pid {
            None => false,
            Some(pid) => re.is_match(pid.as_str()),
        }
    }
}

#[aoc_generator(day4)]
fn parse_input_day4(input: &str) -> Vec<Passport> {
    input
        .split("\n\n")
        .map(|passport_str| parse_passport(passport_str))
        .collect()
}

fn parse_passport(passport_str: &str) -> Passport {
    let kv: Vec<&str> = passport_str
        .lines()
        .flat_map(|line| line.split(" "))
        .collect();
    let mut pass = Passport::new();
    for key_val in kv {
        let pair: Vec<&str> = key_val.split(":").collect();
        match *(pair.get(0).unwrap()) {
            "cid" => pass.cid = Some(String::from(*pair.get(1).unwrap())),
            "byr" => pass.byr = Some(str::parse(*pair.get(1).unwrap()).unwrap()),
            "iyr" => pass.iyr = Some(str::parse(*pair.get(1).unwrap()).unwrap()),
            "eyr" => pass.eyr = Some(str::parse(*pair.get(1).unwrap()).unwrap()),
            "hgt" => {
                pass.hgt_str = Some(str::parse(*pair.get(1).unwrap()).unwrap());
                pass.hgt = Height::parse(*pair.get(1).unwrap());
            }
            "hcl" => pass.hcl = Some(String::from(*pair.get(1).unwrap())),
            "ecl" => pass.ecl = Some(String::from(*pair.get(1).unwrap())),
            "pid" => pass.pid = Some(String::from(*pair.get(1).unwrap())),
            _ => panic!("Found passport code that doesn't match"),
        }
    }
    pass
}

#[aoc(day4, part1)]
fn count_valid_passports(input: &Vec<Passport>) -> usize {
    input.iter().filter(|pass| pass.has_fields()).count()
}

#[aoc(day4, part2)]
fn count_valid_data_passports(input: &Vec<Passport>) -> usize {
    input.iter().filter(|pass| pass.is_valid()).count()
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mellen profile image
Matt Ellen-Tsivintzeli

Again, more javascript. It's in a gist if you like that sort of thing.

Part 1 required far less code than part 2 😋

Collapse
 
bgaster profile image
Benedict Gaster

Here is a Haskell soloution for Day 4:

-- check if a given "passport" field is a valid passport field
isValidField :: (T.Text, T.Text) -> Bool
isValidField (name,v) | name == "byr" = fourAux 1920 2002 
                      | name == "iyr" = fourAux 2010 2020
                      | name == "eyr" = fourAux 2020 2030 

                      | name == "ecl" = v `elem` ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]

                      | name == "hcl" = let h = T.head v == '#'
                                            ts = T.tail v
                                        in h && T.length ts == 6 && elementOf "0123456789abcdef" ts 
                      | name == "pid" = either (const False) (\_ -> T.length v == 9) (decimal v)
                      | name == "hgt" = let (n,t) = (fst $ fromRight (0,"") (decimal (T.takeWhile (not . isAlpha) v)), 
                                                                                      T.dropWhile (not . isAlpha) v)
                                        in (t == "cm" && n >= 150 && n <= 193) || (t == "in" && n >= 59 && n <= 76)
                      | otherwise     = name == "cid"
    where 
        fourAux min max = let n = fst $ fromRight (0,"") (decimal v) 
                          in n >= min && n <= max && T.length v == 4

        elementOf :: String -> T.Text -> Bool
        elementOf xs = T.all (`elem` xs)

-- check if a input field is a actually within the set of valid passport fields
isValidFieldName xs = all (`elem` xs) ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]

isValidPassport :: [(T.Text, T.Text)] -> Bool
isValidPassport xs = all isValidField xs && (isValidFieldName $ map fst xs)

-- generate a list of passports, given a list of input lines
passports :: [T.Text] -> [[(T.Text, T.Text)]]
passports = docs [] []
    where
        docs doc ds [] = doc:ds
        docs doc ds ("":xs) = docs [] (doc:ds) xs    
        docs doc ds (x:xs) = docs (mkKey x ++ doc) ds xs

        mkKey = map (\xs -> (T.takeWhile  (/=':') xs, 
                             T.tail (T.dropWhile  (/=':') xs))) . splitOn " "

main = do xs <- IOT.readFile "day4_input" <&> T.lines 
          print (length $ filter isValidFieldName (map (map fst) $ passports xs)) 
          print (length (filter isValidPassport (passports xs)))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
patryk profile image
Patryk Woziński • Edited

God damn, it was not that easy for me! To be honest, I'm not the best with both algorithms and Elixir, but... anyway AoC is a great chance to improve these skills. I've wasted time making stupid things with Regex. Facepalm.

There is my solution for the first step:

defmodule AdventOfCode.Day4Part1 do
  def calculate(file_path) do
    file_path
    |> read_passports()
    |> Enum.filter(&valid_passport?(&1))
    |> Enum.count()
  end

  defp read_passports(file_path) do
    File.read!(file_path)
    |> String.split("\n\n", trim: true)
    |> Enum.map(&prepare_passport(&1))
  end

  defp prepare_passport(passport) do
    passport
    |> String.splitter("\n", trim: true)
    |> Enum.flat_map(&String.split(&1))
    |> Enum.into(%{}, fn field ->
      field
      |> String.split(":")
      |> List.to_tuple()
    end)
  end

  defp valid_passport?(document) do
    not is_nil(document["byr"]) and
      not is_nil(document["iyr"]) and
      not is_nil(document["eyr"]) and
      not is_nil(document["hgt"]) and
      not is_nil(document["hcl"]) and
      not is_nil(document["ecl"]) and
      not is_nil(document["pid"])
  end
end
Enter fullscreen mode Exit fullscreen mode

And the second step:

defmodule AdventOfCode.Day4Part2 do
  def calculate(file_path) do
    file_path
    |> read_passports()
    |> Enum.filter(&valid_passport?(&1))
    |> Enum.count()
  end

  defp read_passports(file_path) do
    File.read!(file_path)
    |> String.split("\n\n", trim: true)
    |> Enum.map(&prepare_passport(&1))
  end

  defp prepare_passport(passport) do
    passport
    |> String.splitter("\n", trim: true)
    |> Enum.flat_map(&String.split(&1))
    |> Enum.into(%{}, fn field ->
      field
      |> String.split(":")
      |> List.to_tuple()
    end)
  end

  defp valid_passport?(document) do
    document["byr"] |> between?(1920, 2002) and
      document["iyr"] |> between?(2010, 2020) and
      document["eyr"] |> between?(2020, 2030) and
      document["hgt"] |> valid_height?() and
      document["hcl"] |> valid_hair_color?() and
      document["ecl"] |> valid_eye_color?() and
      document["pid"] |> valid_passport_id?()
  end

  defp between?(year, from, to) when is_binary(year),
    do: String.to_integer(year) |> between?(from, to)

  defp between?(year, from, to) when is_integer(year), do: year in from..to

  defp between?(nil, _from, _to), do: false

  defp valid_height?(full_height) when is_binary(full_height) do
    case Integer.parse(full_height) do
      {height, "in"} when height in 59..76 -> true
      {height, "cm"} when height in 150..193 -> true
      _ -> false
    end
  end

  defp valid_height?(nil), do: false

  defp valid_hair_color?(hair_color) when is_binary(hair_color),
    do: String.match?(hair_color, ~r/^#[0-9a-f]{6}$/)

  defp valid_hair_color?(nil), do: false

  defp valid_eye_color?(eye_color) when is_binary(eye_color),
    do: eye_color in ~w(amb blu brn gry grn hzl oth)

  defp valid_eye_color?(nil), do: false

  defp valid_passport_id?(passport_id) when is_binary(passport_id),
    do: String.match?(passport_id, ~r/^[0-9]{9}$/)

  defp valid_passport_id?(nil), do: false
end
Enter fullscreen mode Exit fullscreen mode
Collapse
 
aspittel profile image
Ali Spittel

I hate problems like this:

class Validator:
    def __init__(self, passport):
        self.passport = passport

    def check_field_count(self):
        return len(self.passport) == 8 or (len(self.passport) == 7 and 'cid' not in self.passport)

    def check_year(self, key, start, end):
        return len(self.passport[key]) == 4 and int(self.passport[key]) >= start and int(self.passport[key]) <= end

    def check_byr(self):
        return self.check_year('byr', 1920, 2002)

    def check_iyr(self):
        return self.check_year('iyr', 2010, 2020)

    def check_eyr(self):
        return self.check_year('eyr', 2020, 2030)

    def check_hcl(self):
        return self.passport['hcl'][0] == "#" and self.passport['hcl'][1:].isalnum()

    def check_ecl(self):
        return self.passport['ecl'] in ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth']

    def check_pid(self):
        return len(self.passport['pid']) == 9

    def check_hgt(self):
        if self.passport['hgt'][-2:] == "cm":
            return int(self.passport['hgt'][:-2]) >= 150 and int(self.passport['hgt'][:-2]) <= 193
        elif self.passport['hgt'][-2:] == "in":
            return int(self.passport['hgt'][:-2]) >= 59 and int(self.passport['hgt'][:-2]) <= 76

    def is_valid(self):
        return (self.check_field_count() and self.check_byr() and self.check_iyr() and self.check_eyr() 
            and self.check_hcl() and self.check_ecl() and self.check_pid() and self.check_hgt())


def get_passports(inp):
    passports = []
    passport = {}
    for line in inp:
        if line != "\n":
            line = line.rstrip().split(" ")
            line = [field.split(":") for field in line]
            for field in line:
                passport[field[0]] = field[1]
        else:
            passports.append(passport)
            passport = {}
    passports.append(passport)
    return passports


with open('input.txt') as inp:
    passports = get_passports(inp)
    validators = [Validator(passport) for passport in passports]
    part_1_count = 0
    part_2_count = 0
    for validator in validators:
        if validator.check_field_count(): 
            part_1_count += 1
        if validator.is_valid(): 
            part_2_count += 1                        

    print(part_1_count) 
    print(part_2_count)                
Enter fullscreen mode Exit fullscreen mode
Collapse
 
grantfinneman profile image
Grant Finneman

Thank you so much for the clear and concise python, I'm new to python and thought this would be an excellent way to learn it. I figured this one out eventually and thought I would come here to see how someone else did it. I don't understand how yours doesn't throw a key error when trying to access dictionary keys that aren't there. I need to learn more about classes but I don't know why this works. If you could point me in the right direction I'd greatly appreciate it. Thank you again for the wonderful example

Collapse
 
willsmart profile image
willsmart • Edited

Plain forgot to break out of the comfort zone and use something other than javascript :|
I'll try C tomorrow

Here's today:

const input = require('fs')
  .readFileSync('4.txt', 'utf-8')
  .split(/\n{2,}/g)
  .map(s => Object.fromEntries(s.split(/\s+/g).map(s => s.split(':'))));

console.log({
  input: input.map(v => ({ v: JSON.stringify(v), isValid: isValid(v), check: check(v) })),
  count: input.reduce((acc, v) => acc + isValid(v), 0),
});

function check(v) {
  return ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']
    .flatMap(k => (k in v && !validPair(k, v[k]) ? k : []))
    .join(' ');
}
function isValid(v) {
  return ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'].reduce(
    (acc, k) => acc && k in v && validPair(k, v[k]),
    true
  );
}

function validPair(k, v) {
  let m;
  switch (k) {
    case 'byr':
      return v.length === 4 && v >= 1920 && v <= 2002;
    case 'iyr':
      return v.length === 4 && v >= 2010 && v <= 2020;
    case 'eyr':
      return v.length === 4 && v >= 2020 && v <= 2030;
    case 'hgt':
      if ((m = /^([\d.]+)cm$/.exec(v))) return m[1] >= 150 && m[1] <= 193;
      if ((m = /^([\d.]+)in$/.exec(v))) return m[1] >= 59 && m[1] <= 76;
      return false;
    case 'hcl':
      return /^#[0-9a-f]{6}$/.test(v);
    case 'ecl':
      return ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'].includes(v);
    case 'pid':
      return /^[0-9]{9}$/.test(v);
  }
}
Enter fullscreen mode Exit fullscreen mode

(added check as a way to see which field validator was broken when I failed part 2 the first time. It was a stupid typo in 'ecl')

Collapse
 
galoisgirl profile image
Anna

Not my finest work, I took advantage of the fact that some problems didn't arise in the test data. Then again, this isn't real life, it's a game and I got the stars. 😉

Part 2 here.

   IDENTIFICATION DIVISION.
   PROGRAM-ID. AOC-2020-04-1.
   AUTHOR. ANNA KOSIERADZKA.

   ENVIRONMENT DIVISION.
   INPUT-OUTPUT SECTION.
   FILE-CONTROL.
       SELECT INPUTFILE ASSIGN TO "d4.input"
       ORGANIZATION IS LINE SEQUENTIAL.

   DATA DIVISION.
   FILE SECTION.
     FD INPUTFILE
     RECORD IS VARYING IN SIZE FROM 1 to 99
     DEPENDING ON REC-LEN.
     01 INPUTRECORD PIC X(99).
   WORKING-STORAGE SECTION.
     01 FILE-STATUS PIC 9 VALUE 0.
     01 REC-LEN PIC 9(2) COMP.
     01 WS-ROW PIC X(16) OCCURS 8 TIMES.
     01 WS-CHAR PIC X.

   LOCAL-STORAGE SECTION.
     01 CORRECT-PASSPORTS UNSIGNED-INT VALUE 0.
     01 FOUND-FIELDS UNSIGNED-INT VALUE 0.
     01 STRING-PTR UNSIGNED-INT VALUE 1.
     01 I UNSIGNED-INT VALUE 1.

   PROCEDURE DIVISION.
   001-MAIN.
       OPEN INPUT INPUTFILE.
       PERFORM 002-READ UNTIL FILE-STATUS = 1.
       CLOSE INPUTFILE.
       PERFORM 004-NEXT-PASSPORT.
       DISPLAY CORRECT-PASSPORTS.
       STOP RUN.

   002-READ.
        READ INPUTFILE
            AT END MOVE 1 TO FILE-STATUS
            NOT AT END PERFORM 003-PROCESS-RECORD
        END-READ.

   003-PROCESS-RECORD.
       IF REC-LEN = 0 THEN
          PERFORM 004-NEXT-PASSPORT
       ELSE 
          PERFORM 005-PROCESS-ROW
       END-IF.

   004-NEXT-PASSPORT.
       IF FOUND-FIELDS = 7 THEN 
          ADD 1 TO CORRECT-PASSPORTS
       END-IF.
       MOVE 0 TO FOUND-FIELDS.

   005-PROCESS-ROW.
       MOVE 1 TO STRING-PTR.
       PERFORM VARYING I FROM 1 BY 1 UNTIL I > 8
         UNSTRING INPUTRECORD DELIMITED BY SPACE INTO WS-ROW(I)
         WITH POINTER STRING-PTR
       END-PERFORM.

       PERFORM VARYING I FROM 1 BY 1 UNTIL I > 8
          MOVE WS-ROW(I)(1:1) TO WS-CHAR
          IF NOT WS-CHAR ='c' AND NOT WS-CHAR = ' ' THEN
             ADD 1 TO FOUND-FIELDS
          END-IF
       END-PERFORM.
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rpalo profile image
Ryan Palo

This was a long one, but I learned a ton about the <string.h> library. I also incremented a macro by 1 and spent 3 hours chasing a segfault. So, all in all, I think it sounds like we all had similar days. There are also several edge cases that I'm pretty sure my code doesn't cover, BUT that doesn't matter because this is AoC and it's not wrong if you get the stars. Right? Right?

Day4.h:

#ifndef AOC2020_DAY4_H
#define AOC2020_DAY4_H

/// Day 4: Passport Processing
///
/// Pick through passports made up of key/value pairs to figure out
/// which ones are valid.

#include <stdlib.h>
#include <stdbool.h>

#define NUM_PASS_FIELDS 8  ///< Number of fields in a SimplePassport
#define MAX_ENTRY_SIZE 20  ///< Max size of possible value in key/value
#define KEY_SIZE 4         ///< Size of a key in key/value
#define HAIR_COLOR_SIZE 8  ///< Size of a well-formed hair color
#define PID_SIZE 10        ///< Size of a well-formed PID

/// A simple passport just has certain fields or not.  Valid ones have
/// them all, with 'cid' being optional.
typedef struct {
  bool byr;
  bool iyr;
  bool eyr;
  bool hgt;
  bool hcl;
  bool ecl;
  bool pid;
  bool cid;
} SimplePassport;

/// Parses the input file, which is a series of passports.  Each key/val
/// is separated by a space or newline.  Passports are separated by 
/// two newlines.  Returns a list of passport structs.
SimplePassport* parse_simple_passports(const char* filename, int* count);

/// Counts the number of valid passports.  Passports are valid if
/// the have all keys, except CID is optional.
int part1(SimplePassport* passes, int count);

// ============== Part 2 ================== //

/// Possible values for height units: none, inches, or centimeters.
typedef enum {
  HT_BAD,
  HT_IN,
  HT_CM,
} HeightUnit;

/// A height is a measurement associated with a set of units.
typedef struct {
  int value;
  HeightUnit units;
} Height;

/// Possible options for eye color
typedef enum {
  EYE_BAD,
  EYE_AMBER,
  EYE_BLUE,
  EYE_BROWN,
  EYE_GREY,
  EYE_GREEN,
  EYE_HAZEL,
  EYE_OTHER,
} EyeColor;

/// A fancy passport has strict value validation for all fields.
/// Note: all fields here must be present to win.
typedef struct {
  /// Birth Year: 1920 <= x <= 2002
  int byr; 
  /// Issue Year: 2010 <= x <= 2020
  int iyr;
  /// Expiration Year: 2020 <= x <= 2030
  int eyr;
  /// Height: 150 <= cm <= 193 || 59 <= in <= 76
  Height hgt;
  /// Hair Color: # followed by 6 chars 0-9 or a-f
  char hcl[8];
  /// Eye Color: amb | blu | brn | gry | grn | hzl | oth
  EyeColor ecl;
  /// Passport ID : Exactly 9 digits.  (Storing 10 to find invalid ones)
  char pid[10];
} FancyPassport;

/// Parse fancy passports from an input file.  The number of them
/// is stored in 'count'.
FancyPassport* parse_fancy_passports(const char* filename, int* count);

/// Counts the number of valid fancy passports based on the rules above.
int part2(FancyPassport* passes, int count);

/// Runs both parts.
int day4(void);
#endif
Enter fullscreen mode Exit fullscreen mode

Day4.c:

#include "Day4.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/// Loops through a file and counts all instances of double-newlines.
/// Adds one at the end for the last entry which doesn't have a trailing
/// double-newline.
static int count_passports(FILE* fp) {
  int count = 0;
  while (!feof(fp)) {
    if (getc(fp) == '\n' && getc(fp) == '\n') count++;
  }
  count++; // No double newline after last one.

  rewind(fp);
  return count;
}

/// Parses a single passport from a file.  Leaves the file pointer 
/// after the trailing double-newline, ready to parse the next one.
static SimplePassport parse_simple_passport(FILE* fp) {
  char key[4];
  char value[20];
  SimplePassport passport = {0};

  while (!feof(fp) && getc(fp) != '\n') {
    memset(key, 0, 4);
    memset(value, 0, 20);
    fseek(fp, -1, SEEK_CUR); // Un-eat the previous char because we need it.
    fgets(key, KEY_SIZE, fp);

    fscanf(fp, "%s", value);  // Eat the colon, value
    getc(fp);  // Eat white space?

    if (strcmp(key, "byr") == 0) passport.byr = true;
    else if (strcmp(key, "iyr") == 0) passport.iyr = true;
    else if (strcmp(key, "eyr") == 0) passport.eyr = true;
    else if (strcmp(key, "hgt") == 0) passport.hgt = true;
    else if (strcmp(key, "hcl") == 0) passport.hcl = true;
    else if (strcmp(key, "ecl") == 0) passport.ecl = true;
    else if (strcmp(key, "pid") == 0) passport.pid = true;
    else if (strcmp(key, "cid") == 0) passport.cid = true;
    else {
      printf("Unrecognized key: %s\n", key);
    }
  }
  return passport;
}

SimplePassport* parse_simple_passports(const char* filename, int* count) {
  FILE* fp;
  fp = fopen(filename, "r");
  if (fp == NULL) {
    printf("Couldn't open file.\n");
    exit(EXIT_FAILURE);
  }

  *count = count_passports(fp);
  SimplePassport* passes = (SimplePassport*)malloc(sizeof(SimplePassport) * *count);

  for (int i = 0; i < *count; i++) {
    passes[i] = parse_simple_passport(fp);
  }

  fclose(fp);
  return passes;
}

int part1(SimplePassport* passes, int count) {
  int invalid = 0;
  for (int i = 0; i < count; i++) {
    bool* p = (bool*)&passes[i];

    // Iterates over each field of the passport by using the bytes of
    // the struct as an array of bools.  Which should be OK?
    for (int j = 0; j < NUM_PASS_FIELDS - 1; j++) {
      if (p[j] == false) {
        invalid++;
        break;
      };
    }
  }
  return count - invalid;
}

// ================= Part 2 ===================== //

/// Parses a height string to a Height struct.  Well-formed strings
/// are [0-9]+(in|cm).  If it's invalid, leaves the value as 0 and
/// the units as HT_BAD.
static Height parse_height(char* value) {
  Height h;
  int possible_value;
  char units[4];
  sscanf(value, "%d%s", &possible_value, units);

  if (strcmp(units, "in") == 0) {
    h.value = possible_value;
    h.units = HT_IN;
  } else if (strcmp(units, "cm") == 0) {
    h.value = possible_value;
    h.units = HT_CM;
  } else {
    h.value = 0;
    h.units = HT_BAD;
  }
  return h;
}

/// Parses an EyeColor from a string.
static EyeColor parse_eye_color(char* value) {
  if (strcmp(value, "amb") == 0) return EYE_AMBER;
  if (strcmp(value, "blu") == 0) return EYE_BLUE;
  if (strcmp(value, "brn") == 0) return EYE_BROWN;
  if (strcmp(value, "gry") == 0) return EYE_GREY;
  if (strcmp(value, "grn") == 0) return EYE_GREEN;
  if (strcmp(value, "hzl") == 0) return EYE_HAZEL;
  if (strcmp(value, "oth") == 0) return EYE_OTHER;
  return EYE_BAD;
}

/// Prints out a FancyPassport for debugging.
static void print_fancy_passport(FancyPassport* p) {
  printf("Passport:\n");
  printf("BYR: %d\nIYR: %d\nEYR: %d\n", p->byr, p->iyr, p->eyr);
  printf("HGT: %d-%d\nHCL: %s\nECL: %d\n", p->hgt.value, p->hgt.units, p->hcl, p->ecl);
  printf("PID: %s\n", p->pid);
}

/// Parses a single fancy passport from a file.
static FancyPassport parse_fancy_passport(FILE* fp) {
  char key[KEY_SIZE];
  char value[20];
  FancyPassport passport = {0};

  while (!feof(fp) && getc(fp) != '\n') {
    memset(key, 0, 4);
    memset(value, 0, 20);
    fseek(fp, -1, SEEK_CUR); // Un-eat the previous char because we need it.
    fgets(key, KEY_SIZE, fp);

    fscanf(fp, ":%s", value);  // Eat the colon, value
    getc(fp);  // Eat white space

    if (strcmp(key, "byr") == 0) passport.byr = atoi(value);
    else if (strcmp(key, "iyr") == 0) passport.iyr = atoi(value);
    else if (strcmp(key, "eyr") == 0) passport.eyr = atoi(value);
    else if (strcmp(key, "hgt") == 0) passport.hgt = parse_height(value);
    else if (strcmp(key, "hcl") == 0) {
      if (strlen(value) != HAIR_COLOR_SIZE - 1) continue;  // Leave it empty
      strncpy(passport.hcl, value, HAIR_COLOR_SIZE - 1);
    }
    else if (strcmp(key, "ecl") == 0) passport.ecl = parse_eye_color(value);
    else if (strcmp(key, "pid") == 0) {
      if (strlen(value) != PID_SIZE - 1) continue;  // Leave it empty
      strncpy(passport.pid, value, PID_SIZE - 1);
    } 
    else if (strcmp(key, "cid") == 0) continue;
    else {
      printf("Unrecognized key: %s\n", key);
    }
  }

  return passport;
}

FancyPassport* parse_fancy_passports(const char* filename, int* count) {
  FILE* fp;
  fp = fopen(filename, "r");
  if (fp == NULL) {
    printf("Couldn't open file.\n");
    exit(EXIT_FAILURE);
  }

  *count = count_passports(fp);
  FancyPassport* passes = (FancyPassport*)malloc(sizeof(FancyPassport) * *count);

  for (int i = 0; i < *count; i++) {
    passes[i] = parse_fancy_passport(fp);
  }

  fclose(fp);
  return passes;
}

/// Checks whether a hair color is valid.
static bool valid_hair_color(char* color) {
  if (color[0] != '#') return false;
  for (int i = 1; color[i]; i++) {
    if ((color[i] < '0' || color[i] > '9') && (color[i] < 'a' || color[i] > 'f')) {
      return false;
    }
  }
  return true;
}

/// Checks whether a PID is valid.
static bool valid_pid(char* value) {
  if (strlen(value) != PID_SIZE - 1) return false;
  for (int i = 0; value[i]; i++) {
    if (value[i] < '0' || value[i] > '9') return false;
  }
  return true;
}

/// Finger-saving macro for part2: increment the invalids and continue
#define INC_BAD {invalid++; continue;}

int part2(FancyPassport* passes, int count) {
  int invalid = 0;
  for (int i = 0; i < count; i++) {
    FancyPassport p = passes[i];

    if (p.byr < 1920 || p.byr > 2002) INC_BAD
    if (p.iyr < 2010 || p.iyr > 2020) INC_BAD
    if (p.eyr < 2020 || p.eyr > 2030) INC_BAD
    if (p.hgt.units == HT_BAD) INC_BAD
    if (p.hgt.units == HT_CM && (p.hgt.value < 150 || p.hgt.value > 193)) INC_BAD
    if (p.hgt.units == HT_IN && (p.hgt.value < 59 || p.hgt.value > 76)) INC_BAD
    if (!valid_hair_color(p.hcl)) INC_BAD
    if (p.ecl == EYE_BAD) INC_BAD
    if (!valid_pid(p.pid)) INC_BAD
  }
  return count - invalid;
}

int day4() {
  int count;
  SimplePassport* passes = parse_simple_passports("data/day4.txt", &count);
  printf("====== Day 4 ======\n");
  printf("Part 1: %d\n", part1(passes, count));
  free(passes);

  count = 0;
  FancyPassport* passes2 = parse_fancy_passports("data/day4.txt", &count);
  printf("Part 2: %d\n", part2(passes2, count));
  free(passes2);
  return EXIT_SUCCESS;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
klnjmm profile image
Jimmy Klein

Hi,

A lot of class for this one in order to limit each class responsability.

Full size here : Advent of Code - Day 4

Advent of Code - Day 4

Collapse
 
sleeplessbyte profile image
Derk-Jan Karrenbeld • Edited

I feel this reads as quite elegant in Ruby -- or at least my implementation of it.

Hoping on something more interesting to do for Day 5!

require 'benchmark'

class Passport
  RULES = {
    byr: -> (value) { /^[0-9]{4}$/.match?(value) && (1920..2002).cover?(value.to_i) },
    iyr: -> (value) { /^[0-9]{4}$/.match?(value) && (2010..2020).cover?(value.to_i) },
    eyr: -> (value) { /^[0-9]{4}$/.match?(value) && (2020..2030).cover?(value.to_i) },
    hgt: -> (value) {
      match = /(^[1-9][0-9]+)(cm|in)$/.match(value)

      match && (
        (match[2] == 'cm' && (150..193).cover?(match[1].to_i)) ||
        (match[2] == 'in' && (59..76).cover?(match[1].to_i))
      )
    },
    hcl: -> (value) { /^\#[0-9a-f]{6}$/.match? value },
    ecl: -> (value) { %w[amb blu brn gry grn hzl oth].include?(value) },
    pid: -> (value) { /^[0-9]{9}$/.match? value }
  }

  def self.from(lines)
    fields = lines.split(' ')

    new(fields.each_with_object({}) do |kv, results|
      k, v = kv.chomp.split(':')
      results[k.to_sym] = v
    end)
  end

  def initialize(fields)
    self.fields = fields
  end

  def [](field)
    fields[field]
  end

  def valid?
    RULES.keys.all? { |field| RULES[field].(self[field]) }
  end

  private

  attr_accessor :fields
end

data = File.read('input.txt')
passports = data
  .split(/\n\n/)
  .map do |l|
    Passport.from(l)
  end

Benchmark.bmbm do |b|
  b.report do
    puts passports.count(&:valid?)
  end
end
Enter fullscreen mode Exit fullscreen mode