Skip to content

Instantly share code, notes, and snippets.

@gacardinal
Created December 3, 2020 04:32
Show Gist options
  • Save gacardinal/d8f61de29b1e795dab0bc4ff7628fa59 to your computer and use it in GitHub Desktop.
Save gacardinal/d8f61de29b1e795dab0bc4ff7628fa59 to your computer and use it in GitHub Desktop.
Advent of Code 2020 Day 2
import { readFileSync } from 'fs';
type PasswordPolicy = {
[key: string]: any
}
type OcurrencePasswordPolicy = {
[key: string]: { min: number, max: number }
}
type PositionPasswordPolicy = {
[key: string]: number[]
}
type ParsingStrategy<T> = (policy: string) => T;
const parseOcurrencePolicies = (policy: string): OcurrencePasswordPolicy => {
const [ range, character ] = policy.split(' ');
const [ min, max ] = range.split('-').map(x => parseInt(x));
return { [character]: { min, max } };
}
const parsePositionPolicy = (policy: string): PositionPasswordPolicy => {
const [ positions, character ] = policy.split(' ');
return { [character]: positions.split('-').map(x => parseInt(x)) };
}
function parsePasswordEntry<T>(str: string, parsingStrategy: ParsingStrategy<T>) {
const split = str.split(': ');
return {
policy: parsingStrategy(split[0]),
password: split[1]
};
}
function countOcurrences(str: string, char: string) {
return new Array(...str).filter(c => c === char).length;
};
const enforceOcurrencePolicy = (password: string, policy: OcurrencePasswordPolicy) => {
return Object.keys(policy).every(character => {
const characterPolicy = policy[character];
const ocurrences = countOcurrences(password, character);
return ocurrences >= characterPolicy.min && ocurrences <= characterPolicy.max;
});
}
const enforcePositionPolicy = (password: string, policy: PositionPasswordPolicy) => {
return Object.keys(policy).every(character => {
const characterPolicy = policy[character];
return [
password[characterPolicy[0] - 1],
password[characterPolicy[1] - 1]
].filter(x => x === character).length === 1;
});
}
const raw = readFileSync('input.txt').toString('utf8').split('\n');
const chp1Passwords = raw.map(x => parsePasswordEntry(x, parseOcurrencePolicies));
const chp1ValidPasswords = chp1Passwords.filter(pw => enforceOcurrencePolicy(pw.password, pw.policy));
console.log(`chapter 1: ${chp1ValidPasswords.length}`);
const chp2Passwords = raw.map(x => parsePasswordEntry(x, parsePositionPolicy));
const chp2ValidPasswords = chp2Passwords.filter(pw => enforcePositionPolicy(pw.password, pw.policy));
console.log(`chapter 2: ${chp2ValidPasswords.length}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment