# AoC Day 2 – Password Philosophy

This is a solution to Advent of Code 2020 day 2, written in Raku and Python.

### Part One

To try to debug the problem, they have created a list (your puzzle input) of passwords (according to the corrupted database) and the corporate policy when that password was set.

Each line gives the password policy and then the password. The password policy indicates the lowest and highest number of times a given letter must appear for the password to be valid.

How many passwords are valid according to their policies?

#### Raku

  my @entries = '2-input.txt'.IO.lines;

say [+] @entries.map(
-> $entry { my ($l, $h,$c, $str) =$entry.match( /(\d+) '-' (\d+) \s+ (\w) ':' \s+ (\w+)/ ).values;
$l <=$str.comb.Bag{~$c} <=$h
})
538


#### Python

  from collections import Counter

entries = open('2-input.txt', 'r').read().splitlines()

def passCheck(entry):
lowhigh, c, password = entry.split(' ')
low, high = map(lambda s: int(s), lowhigh.split('-'))
c = c
return low <= Counter(password)[c] <= high

valid = filter(lambda e: passCheck(e), entries)

print(len(list(valid)))
538


### Part Two

Each policy actually describes two positions in the password, where 1 means the first character, 2 means the second character, and so on. (Be careful; Toboggan Corporate Policies have no concept of "index zero"!) Exactly one of these positions must contain the given letter. Other occurrences of the letter are irrelevant for the purposes of policy enforcement.

How many passwords are valid according to the new interpretation of the policies?

#### Raku

  my @entries = '2-input.txt'.IO.lines;

say [+] @entries.map(
-> $entry { my ($l, $h,$c, $str) =$entry.match( /(\d+) '-' (\d+) \s+ (\w) ':' \s+ (\w+)/ ).values;
my @chars = $str.comb; @chars[$l - 1] eq $c xor @chars[$h - 1] eq \$c
})
489


#### Python

  from collections import Counter

entries = open('2-input.txt', 'r').read().splitlines()

def passCheck(entry):
lowhigh, c, password = entry.split(' ')
low, high = map(lambda s: int(s), lowhigh.split('-'))
c = c
return (password[low - 1] == c ) ^ (password[high - 1] == c)

valid = filter(lambda e: passCheck(e), entries)

print(len(list(valid)))
489

comments powered by Disqus