From 5045284462c8e67a5430367c5c92398f0ed7e5fb Mon Sep 17 00:00:00 2001 From: Jan Tuomi Date: Wed, 2 Dec 2020 09:57:07 +0200 Subject: Solve 2.2 --- day2/index.ts | 44 ++++++++++++++++++++++++++++++++++++++------ 1 file changed, 38 insertions(+), 6 deletions(-) diff --git a/day2/index.ts b/day2/index.ts index e42e005..8b3199a 100644 --- a/day2/index.ts +++ b/day2/index.ts @@ -2,14 +2,21 @@ import { of } from "rxjs"; import { concatAll, count, filter, map, take } from 'rxjs/operators'; import { ExerciseModuleFunc } from "../types"; -interface Row { +interface Row1 { min: number; max: number; letter: string; pwd: string; } -const parse = (line: string): Row => { +interface Row2 { + index1: number; + index2: number; + letter: string; + pwd: string; +} + +const parse1 = (line: string): Row1 => { const re = /(\d+)-(\d+) (\w{1}): (\w+)/; const match = line.match(re); @@ -21,7 +28,19 @@ const parse = (line: string): Row => { } } -const isValid = (r: Row): boolean => { +const parse2 = (line: string): Row2 => { + const re = /(\d+)-(\d+) (\w{1}): (\w+)/; + const match = line.match(re); + + return { + index1: Number(match[1]) - 1, + index2: Number(match[2]) - 1, + letter: match[3], + pwd: match[4] + } +} + +const isValid1 = (r: Row1): boolean => { let count = 0; r.pwd.split("").forEach(char => { if (char === r.letter) { @@ -31,17 +50,30 @@ const isValid = (r: Row): boolean => { return count >= r.min && count <= r.max; } +const isValid2 = (r: Row2): boolean => { + const a = r.pwd[r.index1] === r.letter; + const b = r.pwd[r.index2] === r.letter; + return (a && !b) || (!a && b); +} + const day2: ExerciseModuleFunc = async (input: string) => { const lines = input.split("\n"); const prom1 = of(lines).pipe( concatAll(), - map(parse), - filter(isValid), + map(parse1), + filter(isValid1), + count() + ).toPromise(); + + const prom2 = of(lines).pipe( + concatAll(), + map(parse2), + filter(isValid2), count() ).toPromise(); - return [await prom1]; + return [await prom1, await prom2]; } export default day2; -- cgit v1.3