aboutsummaryrefslogtreecommitdiffstats
path: root/day2/index.ts
blob: e42e005cf07339ebbe25640d26ee8d26300e3ec4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { of } from "rxjs";
import { concatAll, count, filter, map, take } from 'rxjs/operators';
import { ExerciseModuleFunc } from "../types";

interface Row {
  min: number;
  max: number;
  letter: string;
  pwd: string;
}

const parse = (line: string): Row => {
  const re = /(\d+)-(\d+) (\w{1}): (\w+)/;
  const match = line.match(re);

  return {
    min: Number(match[1]),
    max: Number(match[2]),
    letter: match[3],
    pwd: match[4]
  }
}

const isValid = (r: Row): boolean => {
  let count = 0;
  r.pwd.split("").forEach(char => {
    if (char === r.letter) {
      count += 1;
    }
  });
  return count >= r.min && count <= r.max;
}

const day2: ExerciseModuleFunc = async (input: string) => {
  const lines = input.split("\n");

  const prom1 = of(lines).pipe(
    concatAll(),
    map(parse),
    filter(isValid),
    count()
  ).toPromise();

  return [await prom1];
}

export default day2;