From cca3701cd6bb6c479aeb1ece71aa5bae5383ae65 Mon Sep 17 00:00:00 2001 From: Jan Tuomi Date: Tue, 1 Dec 2020 14:13:46 +0200 Subject: Solve 1.2 --- day1/index.ts | 33 +++++++++++++++++++++++++++++---- types.d.ts | 2 +- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/day1/index.ts b/day1/index.ts index 93f0ec6..e93a688 100644 --- a/day1/index.ts +++ b/day1/index.ts @@ -1,20 +1,45 @@ import { of } from "rxjs"; -import { filter, map } from 'rxjs/operators'; +import { concatAll, filter, map } from 'rxjs/operators'; import { ExerciseModuleFunc } from "../types"; type Pair = [T, K]; +type Triple = [A, B, C]; + +const allTriples = (lst: T[]): Triple[] => { + const results: Triple[] = []; + lst.forEach((a, ai) => { + lst.slice(ai + 1).forEach((b, bi) => { + lst.slice(bi + 1).forEach((c, _ci) => { + results.push([a, b, c]); + }) + }) + }); + return results; +} const day1: ExerciseModuleFunc = async (input: string) => { const numbers = input.split("\n").map(line => Number(line)); - const obs = of(...numbers).pipe( - map((number, index) => [number, numbers.slice(index)] as Pair), + const obs1 = of(...numbers).pipe( + map((number, index) => [number, numbers.slice(index + 1)] as Pair), map(pair => [pair[0], pair[1].find(elem => pair[0] + elem === 2020)] as Pair), filter(pair => pair[1] !== undefined), map(pair => pair[0] * pair[1]), map(solution => solution.toString()) ) - return obs.toPromise(); + const first = await obs1.toPromise(); + + const obs2 = of(numbers).pipe( + map(allTriples), + concatAll(), + filter(t => t[0] + t[1] + t[2] === 2020), + map(t => t[0] * t[1] * t[2]), + map(sol => sol.toString()) + ); + + const second = await obs2.toPromise(); + + return [first, second]; } export default day1; diff --git a/types.d.ts b/types.d.ts index e54f71c..5b46e42 100644 --- a/types.d.ts +++ b/types.d.ts @@ -1 +1 @@ -export type ExerciseModuleFunc = (input: string) => Promise; +export type ExerciseModuleFunc = (input: string) => Promise; -- cgit v1.3