Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | 1x 1x 19800x 1x 11539x 1x 3x 3x 3x 3x 3x 160x 3x 3x 160x 160x 14x 3x 160x 14x 3x 14x 14x 1440x 14x 3x 14x 1272x 3x 1x 3x 3x 174x 22512x 449x 3x 1x 2x 2x 2x 2x 440x 92701x 92701x 92701x 2x 1x | const { readFile } = require('../helpers/file')
const { sum } = require('../helpers/math')
const getColumn = (arr, n) => arr.map((c) => c[n])
const hasNoGalaxies = (column) => {
return column.every((element) => element === '.')
}
const expandUniverse = (fileInput) => {
const data = readFile(fileInput)
const emptyColumnIds = []
const emptyLineIds = []
// Construire la matrice
let matrice = []
for (let i = 0; i < data.length; i++) {
matrice[i] = [...data[i]]
}
const nbColumns = matrice[0].length
// Vérifier si une colonne est vide, récupérer son indice
for (let i = 0; i < nbColumns; i++) {
const column = getColumn(matrice, i)
if (hasNoGalaxies(column)) {
emptyColumnIds.push(i)
}
}
for (let i = 0; i < matrice.length; i++) {
if (hasNoGalaxies(matrice[i])) {
emptyLineIds.push(i)
}
}
// Construct expanded universe
for (let i = 0; i < emptyLineIds.length; i++) {
// Create new empty line
const newLine = []
for (let j = 0; j < nbColumns; j++) {
newLine.push('.')
}
matrice.splice(emptyLineIds[i] + i, 0, newLine)
}
for (let i = 0; i < emptyColumnIds.length; i++) {
for (let k = 0; k < matrice.length; k++) {
matrice[k].splice(emptyColumnIds[i] + i, 0, '.')
}
}
return matrice
}
const getGalaxiesLocations = (galaxies) => {
let galaxiesLocations = []
for (let i = 0; i < galaxies.length; i++) {
for (let j = 0; j < galaxies[0].length; j++) {
if (galaxies[i][j] === '#') {
galaxiesLocations.push([i, j])
}
}
}
return galaxiesLocations
}
const resolvePuzzle = (input) => {
// Calculer l'univers étendu
const expandedUniverse = expandUniverse(input)
// Calculer les localisations de chaque galaxie dans la matrice
const locations = getGalaxiesLocations(expandedUniverse)
// Calculer les distances entre les galaxies
let distances = []
for (let i = 0; i < locations.length; i++) {
for (let j = i + 1; j < locations.length; j++) {
let [galaxyX, galaxyY] = locations[i]
let [otherGalaxyX, otherGalaxyY] = locations[j]
distances.push(
Math.abs(
Math.abs(otherGalaxyX - galaxyX) + Math.abs(otherGalaxyY - galaxyY)
)
)
}
}
return sum(distances)
}
module.exports = {
hasNoGalaxies,
resolvePuzzle,
expandUniverse,
getGalaxiesLocations,
}
|