Skip to content

Commit

Permalink
better regexp
Browse files Browse the repository at this point in the history
  • Loading branch information
shahata committed Dec 2, 2023
1 parent 152578d commit 5b1a7e0
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 6 deletions.
8 changes: 3 additions & 5 deletions src/2023/day01.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(`(?=(?<digit>[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;
Expand Down
2 changes: 1 addition & 1 deletion src/2023/day02.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
Expand Down

0 comments on commit 5b1a7e0

Please sign in to comment.