day02.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { reduce } from "fp-ts/lib/Array";
  2. import { pipe } from "fp-ts/lib/function";
  3. import { moves } from "./input";
  4. import { moves as testMoves } from "./input.test";
  5. const position = pipe(
  6. moves,
  7. reduce([0, 0], ([horizontal, depth], [dir, len]) => {
  8. switch (dir) {
  9. case "forward":
  10. return [horizontal + len, depth];
  11. case "down":
  12. return [horizontal, depth + len];
  13. case "up":
  14. return [horizontal, depth - len];
  15. default:
  16. return [horizontal, depth];
  17. }
  18. })
  19. );
  20. console.log("the final position is", position);
  21. console.log("the product of position coordinates is", position[0] * position[1]);
  22. const positionWithAim = pipe(
  23. moves,
  24. reduce([0, 0, 0], ([aim, horizontal, depth], [dir, len]) => {
  25. switch (dir) {
  26. case "down":
  27. return [aim + len, horizontal, depth];
  28. case "up":
  29. return [aim - len, horizontal, depth];
  30. case "forward":
  31. return [aim, horizontal + len, depth + (aim * len)];
  32. default:
  33. return [aim, horizontal, depth];
  34. }
  35. })
  36. );
  37. console.log("the final position with aim is", positionWithAim);
  38. console.log("the product of position coordinates is", positionWithAim[1] * positionWithAim[2]);