Guest User

AoC 2023 - Day 11 - JS

a guest
Dec 11th, 2023
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. // Day 11 - year 2023
  2. const input = require("fs").readFileSync("input.txt", "utf8").split("\n");
  3.  
  4. const is_empty_col = Array(input[0].length).fill(true);
  5. const is_empty_row = Array(input.length).fill(true);
  6.  
  7. const galaxies = [];
  8.  
  9. input.forEach((row, y) => {
  10. row.split("").forEach((ch, x) => {
  11. if (ch === '#') {
  12. galaxies.push({ x, y });
  13. is_empty_col[x] = false;
  14. is_empty_row[y] = false;
  15. }
  16. });
  17. });
  18.  
  19. const insert_cols = [];
  20. const insert_rows = [];
  21.  
  22. is_empty_col.forEach((v, col) => { if (v) insert_cols.push(col) });
  23. is_empty_row.forEach((v, row) => { if (v) insert_rows.push(row) });
  24.  
  25. console.log("part 1:", sum_distances(expand(galaxies, 1)));
  26. console.log("part 2:", sum_distances(expand(galaxies, 999999)));
  27.  
  28. function expand(galaxies, displace) {
  29. for (galaxy of galaxies) {
  30. let displace_x = insert_cols.filter(v => v < galaxy.x).length;
  31. let displace_y = insert_rows.filter(v => v < galaxy.y).length;
  32. galaxy.x += displace_x * displace;
  33. galaxy.y += displace_y * displace;
  34. }
  35. return galaxies;
  36. }
  37.  
  38. function sum_distances(galaxies) {
  39. let sum = 0;
  40. for (let i = 0; i < galaxies.length - 1; i++) {
  41. for (let j = i + 1; j < galaxies.length; j++) {
  42. let dist = Math.abs(galaxies[i].x - galaxies[j].x) + Math.abs(galaxies[i].y - galaxies[j].y);
  43. sum += dist;
  44. }
  45. }
  46. return sum;
  47. }
Advertisement
Add Comment
Please, Sign In to add comment