day09.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import * as A from "fp-ts/Array";
  2. import * as RA from "fp-ts/ReadonlyArray";
  3. import * as S from "fp-ts/string";
  4. import * as N from "fp-ts/number";
  5. import { flow, pipe } from "fp-ts/lib/function";
  6. import { heightmap } from "./input";
  7. // import { heightmap } from "./input.test";
  8. import { concatAll } from "fp-ts/lib/Monoid";
  9. type HeightMap = ReadonlyArray<ReadonlyArray<number>>;
  10. const parseHeightMap = (input: string): HeightMap => pipe(
  11. input,
  12. S.split("\n"),
  13. RA.map(flow(S.split(""), RA.map(parseInt)))
  14. );
  15. const localMinima = (heightMap: HeightMap): number[] => {
  16. const minima: number[] = [];
  17. for (let i = 0; i < heightMap.length; i++) {
  18. for (let j = 0; j < heightMap[i].length; j++) {
  19. const up = heightMap[i - 1]?.[j] ?? Number.MAX_VALUE;
  20. const down = heightMap[i + 1]?.[j] ?? Number.MAX_VALUE;
  21. const left = heightMap[i]?.[j - 1] ?? Number.MAX_VALUE;
  22. const right = heightMap[i]?.[j + 1] ?? Number.MAX_VALUE;
  23. const value = heightMap[i][j];
  24. if (value < up && value < down && value < left && value < right) {
  25. minima.push(value);
  26. }
  27. }
  28. }
  29. return minima;
  30. }
  31. const sumOfRiskLevels = pipe(
  32. parseHeightMap(heightmap),
  33. localMinima,
  34. A.map(n => n + 1),
  35. concatAll(N.MonoidSum)
  36. );
  37. console.log(sumOfRiskLevels);