Skip to content

Commit

Permalink
perf: Day 5: If You Give A Seed A Fertilizer
Browse files Browse the repository at this point in the history
  • Loading branch information
mariotacke committed Dec 5, 2023
1 parent 7417fdb commit 2d44cfa
Showing 1 changed file with 15 additions and 14 deletions.
29 changes: 15 additions & 14 deletions day-05-if-you-give-a-seed-a-fertilizer/part2.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,24 @@ module.exports = (input) => {
.filter((pair) => pair.trim().length)
.map((s) => s.split(' ').map((n) => +n));

const finder = parts.slice(1)
const isValidSeed = (seed) => {
for (let i = 0; i < seeds.length; i++) {
if (seed >= seeds[i][0] && seed <= seeds[i][0] + seeds[i][1]) {
return true;
}
}
};

const reverseFinder = parts.slice(1)
.reverse()
.map((map) => {
const lookup = map.slice(1).map((line) => line.split(' ').map((n) => +n));

return (number) => {
let result = number;

for (let i = 0; i < lookup.length; i++) {
const [destination, source, length] = lookup[i];
const [source, destination, length] = lookup[i];

if (number >= source && number <= source + length - 1) {
result = destination + number - source;
Expand All @@ -31,19 +40,11 @@ module.exports = (input) => {
})
.reduce((f, fn) => (n) => fn(f(n)), (n) => n);

let minimum = Infinity;

for (let i = 0; i < seeds.length; i++) {
const [start, length] = seeds[i];
for (let minimum = 0; minimum < Infinity; minimum++) {
const result = reverseFinder(minimum);

for (let j = start; j < start + length; j++) {
const result = finder(j);

if (result < minimum) {
minimum = result;
}
if (isValidSeed(result)) {
return minimum;
}
}

return minimum;
};

0 comments on commit 2d44cfa

Please sign in to comment.