From ebac89476331cb6344f6656d4e2625c7426b48d4 Mon Sep 17 00:00:00 2001 From: Shahar Talmi Date: Mon, 2 Dec 2024 07:30:50 +0200 Subject: [PATCH] refactor --- src/2024/day02.js | 37 ++++++++++++------------------------- 1 file changed, 12 insertions(+), 25 deletions(-) diff --git a/src/2024/day02.js b/src/2024/day02.js index 768b85b7..bccb9c05 100644 --- a/src/2024/day02.js +++ b/src/2024/day02.js @@ -1,32 +1,19 @@ +function isSafe(line) { + const result = line.map((num, i) => i > 0 && num - line[i - 1]).slice(1); + return ( + result.every(num => num >= 1 && num <= 3) || + result.every(num => num <= -1 && num >= -3) + ); +} + export function part1(input) { const lines = input.split("\n").map(line => line.split(" ").map(Number)); - const safe = lines.filter(line => { - const result = line - .map((num, i) => (i === 0 ? 0 : num - line[i - 1])) - .slice(1); - return ( - result.every(num => num >= 1 && num <= 3) || - result.every(num => num <= -1 && num >= -3) - ); - }); - return safe.length; + return lines.filter(isSafe).length; } export function part2(input) { const lines = input.split("\n").map(line => line.split(" ").map(Number)); - const safe = lines.filter(line => { - for (let i = 0; i < line.length; i++) { - const newLine = line.slice(); - newLine.splice(i, 1); - const result = newLine - .map((num, i) => (i === 0 ? 0 : num - newLine[i - 1])) - .slice(1); - if ( - result.every(num => num >= 1 && num <= 3) || - result.every(num => num <= -1 && num >= -3) - ) - return true; - } - }); - return safe.length; + return lines.filter(line => { + return line.map((x, i) => line.toSpliced(i, 1)).find(isSafe); + }).length; }