Skip to content

Commit

Permalink
initial solution
Browse files Browse the repository at this point in the history
  • Loading branch information
shahata committed Dec 1, 2023
1 parent 2ae01e5 commit bf474d6
Show file tree
Hide file tree
Showing 3 changed files with 1,094 additions and 0 deletions.
53 changes: 53 additions & 0 deletions src/2023/day01.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
export function part1(input) {
const lines = input.split('\n');
const nums = lines.map(line => {
const first = +line.split('').find(c => c >= '0' && c <= '9');
const last = +line
.split('')
.reverse()
.find(c => c >= '0' && c <= '9');
return first * 10 + last;
});
return nums.reduce((a, b) => a + b, 0);
}

export function part2(input) {
const letters = [
'zero',
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
];
const lines = input.split('\n');
const nums = lines.map(line => {
const first = letters
.map(n => ({ n, i: line.indexOf(n) }))
.filter(x => x.i > -1)
.sort((a, b) => a.i - b.i)[0].n;
const last = letters
.map(n => ({ n, i: line.lastIndexOf(n) }))
.filter(x => x.i > -1)
.sort((a, b) => b.i - a.i)[0].n;

const a = letters.indexOf(first) <= 9 ? letters.indexOf(first) : +first;
const b = letters.indexOf(last) <= 9 ? letters.indexOf(last) : +last;
return a * 10 + b;
});
return nums.reduce((a, b) => a + b, 0);
}
40 changes: 40 additions & 0 deletions src/2023/day01.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { part1, part2 } from './day01.js';
import readInput from '../utils/read-input.js';

const input = readInput(import.meta.url);

describe('day01 2023', () => {
describe('part1', () => {
it('should work for part 1 examples', () => {
expect(
part1(['1abc2', 'pqr3stu8vwx', 'a1b2c3d4e5f', 'treb7uchet'].join('\n')),
).toEqual(142);
});

it('should work for part 1 input', () => {
expect(part1(input)).toEqual(54953);
});
});

describe('part2', () => {
it('should work for part 2 examples', () => {
expect(
part2(
[
'two1nine',
'eightwothree',
'abcone2threexyz',
'xtwone3four',
'4nineeightseven2',
'zoneight234',
'7pqrstsixteen',
].join('\n'),
),
).toEqual(281);
});

it('should work for part 2 input', () => {
expect(part2(input)).toEqual(53868);
});
});
});
Loading

0 comments on commit bf474d6

Please sign in to comment.