Created
December 11, 2023 10:16
-
-
Save Cluracan/0665fe850f42c58312bce086f71600e4 to your computer and use it in GitHub Desktop.
Day 11
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs') | |
const input = fs.readFileSync('input.txt', 'utf-8').split(/\r\n/).map(line => line.split('')) | |
class Galaxy { | |
row | |
col | |
rowInc = 0 | |
colInc = 0 | |
constructor(row, col) { | |
this.row = row | |
this.col = col | |
} | |
expandGalaxy() { | |
this.row += this.rowInc | |
this.col += this.colInc | |
this.rowInc = 0 | |
this.colInc = 0 | |
} | |
addRowInc() { | |
this.rowInc += 999999 | |
} | |
addColInc() { | |
this.colInc += 999999 | |
} | |
static distance(a, b) { | |
const dx = Math.abs(a.col - b.col) | |
const dy = Math.abs(a.row - b.row) | |
return dx + dy | |
} | |
} | |
//create galaxy array and find empty columns/rows | |
let galaxyArray = [] | |
let emptyRowSpace = new Set(Array.from({ length: (input.length) }, (v, i) => i)) | |
let emptyColSpace = new Set(Array.from({ length: (input[0].length) }, (v, i) => i)) | |
for (let row = 0; row < input.length; row++) { | |
for (let col = 0; col < input[0].length; col++) { | |
if (input[row][col] == '#') { | |
galaxyArray.push(new Galaxy(row, col)) | |
emptyRowSpace.delete(row) | |
emptyColSpace.delete(col) | |
} | |
} | |
} | |
//for each empty col/row, mark glaxies for expansion as necessary... | |
emptyRowSpace.forEach(row => { | |
galaxyArray.forEach(galaxy => { | |
if (galaxy.row > row) { | |
galaxy.addRowInc() | |
} | |
}) | |
}) | |
emptyColSpace.forEach(col => { | |
galaxyArray.forEach(galaxy => { | |
if (galaxy.col > col) { | |
galaxy.addColInc() | |
} | |
}) | |
}) | |
//...then expand! | |
galaxyArray.forEach(galaxy => galaxy.expandGalaxy()) | |
//find distance between all pairs of galaxies | |
let totalDistance = 0 | |
for (let i = 0; i < galaxyArray.length - 1; i++) { | |
for (let j = i + 1; j < galaxyArray.length; j++) { | |
totalDistance += Galaxy.distance(galaxyArray[i], galaxyArray[j]) | |
} | |
} | |
console.log(totalDistance) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment