diff --git a/day5/main.ts b/day5/main.ts index c317b16..c35616f 100644 --- a/day5/main.ts +++ b/day5/main.ts @@ -69,12 +69,9 @@ for (const map of [ function cleanInput(o: number[]): boolean { return o.length === 3; } -function orderBySource(a: number[], b: number[]): number { - return a[1] - b[1]; -} seedToSoil = seedToSoil.filter(cleanInput); -soilToFertilizer = soilToFertilizer.filter(cleanInput).sort(orderBySource); +soilToFertilizer = soilToFertilizer.filter(cleanInput); fertilizerToWater = fertilizerToWater.filter(cleanInput); waterToLight = waterToLight.filter(cleanInput); lightToTemp = lightToTemp.filter(cleanInput); @@ -82,23 +79,23 @@ tempToHumidity = tempToHumidity.filter(cleanInput); humidityToLocation = humidityToLocation.filter(cleanInput); /** - * Given a source input and a sorted list of maps, calculate the destination value - * @param input + * Given a source input and a list of maps, calculate the destination value + * @param source * @param maps in the form of [[dest, sourceFrom, sourceTo]] * @returns */ -function getMapResult(input: number, maps: number[][]): number { - // Get the map corresponding to number - let mapped = -1; +function sourceToDestination(source: number, maps: number[][]): number { + let dest = -1; + // Iterate the maps and find the one that matches the source for (const map of maps) { const sourceFrom = map[1]; const sourceTo = map[1] + map[2] - 1; - if (input >= sourceFrom && input <= sourceTo) { - mapped = map[0] + input - sourceFrom; + if (source >= sourceFrom && source <= sourceTo) { + dest = map[0] + source - sourceFrom; } } - if (mapped > -1) return mapped; - return input; + if (dest > -1) return dest; + return source; } let minimalLocation = Number.MAX_VALUE; @@ -107,13 +104,13 @@ for (const pair of seedsPairs) { trace(JSON.stringify(pair)); const to = pair[0] + pair[1] - 1; for (let seed = pair[0]; seed < to; seed++) { - const soil = getMapResult(seed, seedToSoil); - const fert = getMapResult(soil, soilToFertilizer); - const water = getMapResult(fert, fertilizerToWater); - const light = getMapResult(water, waterToLight); - const temp = getMapResult(light, lightToTemp); - const hum = getMapResult(temp, tempToHumidity); - const loc = getMapResult(hum, humidityToLocation); + const soil = sourceToDestination(seed, seedToSoil); + const fert = sourceToDestination(soil, soilToFertilizer); + const water = sourceToDestination(fert, fertilizerToWater); + const light = sourceToDestination(water, waterToLight); + const temp = sourceToDestination(light, lightToTemp); + const hum = sourceToDestination(temp, tempToHumidity); + const loc = sourceToDestination(hum, humidityToLocation); if (loc < minimalLocation) minimalLocation = loc; } } @@ -151,7 +148,7 @@ function TIC() { let y = 1; if (frames % speed === 0) { - seed.value = getMapResult(seed.value, steps[seed.step].map); + seed.value = sourceToDestination(seed.value, steps[seed.step].map); ++seed.step; if (seed.step >= steps.length) { seed.step = 0;