From 5b1a7e0922f9fba92460eec5592d5b5c39b65f87 Mon Sep 17 00:00:00 2001 From: Shahar Talmi Date: Sat, 2 Dec 2023 10:40:42 +0200 Subject: [PATCH] better regexp --- src/2023/day01.js | 8 +++----- src/2023/day02.js | 2 +- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/2023/day01.js b/src/2023/day01.js index 11ada5c4..9f011e97 100644 --- a/src/2023/day01.js +++ b/src/2023/day01.js @@ -21,13 +21,11 @@ export function part2(input) { 'eight', 'nine', ]; - const reverse = s => s.split('').reverse().join(''); - const regex = new RegExp(`[0-9]|${letters.join('|')}`); - const regex2 = new RegExp(`[0-9]|${reverse(letters.join('|'))}`); + const regex = new RegExp(`(?=(?[0-9]|${letters.join('|')}))`, 'g'); const lines = input.split('\n'); const numbers = lines.map(line => { - const first = line.match(regex).at(0); - const last = reverse(reverse(line).match(regex2).at(0)); + const first = [...line.matchAll(regex)].at(0).groups.digit; + const last = [...line.matchAll(regex)].at(-1).groups.digit; const a = Number.isNaN(+first) ? letters.indexOf(first) : +first; const b = Number.isNaN(+last) ? letters.indexOf(last) : +last; return a * 10 + b; diff --git a/src/2023/day02.js b/src/2023/day02.js index ab5fc44a..99cafa32 100644 --- a/src/2023/day02.js +++ b/src/2023/day02.js @@ -30,7 +30,7 @@ export function part1(input) { export function part2(input) { const games = parse(input); const powers = games.map(({ rounds }) => { - const max = ['red', 'blue', 'green'].map(c => { + const max = ['red', 'green', 'blue'].map(c => { const counts = rounds.flat().filter(({ color }) => color === c); return Math.max(...counts.map(({ count }) => count), 0); });