Skip to content

Commit

Permalink
day 4 initial solution
Browse files Browse the repository at this point in the history
  • Loading branch information
shahata committed Dec 4, 2023
1 parent 9e08dc3 commit ef5bf47
Show file tree
Hide file tree
Showing 3 changed files with 269 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/2023/day04.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
function parse(input) {
return input.split('\n').map(line => {
const [, numbers] = line.split(':');
const [left, right] = numbers
.split('|')
.map(s => s.trim().split(/\s+/).map(Number));
return right.filter(n => left.includes(n)).length;
});
}

export function part1(input) {
const cards = parse(input);
return cards
.map(x => (x > 0 ? Math.pow(2, x - 1) : 0))
.reduce((a, b) => a + b, 0);
}

export function part2(input) {
const cards = parse(input);
const seen = {};
for (let i = 0; i < cards.length; i++) {
seen[i] = 1;
}
for (let i = 0; i < cards.length; i++) {
for (let j = 1; j <= cards[i]; j++) {
seen[i + j] += seen[i];
}
}
return Object.values(seen).reduce((a, b) => a + b, 0);
}
48 changes: 48 additions & 0 deletions src/2023/day04.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { part1, part2 } from './day04.js';
import readInput from '../utils/read-input.js';

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

describe('day04 2023', () => {
describe('part1', () => {
it('should work for part 1 examples', () => {
expect(
part1(
[
'Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53',
'Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19',
'Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1',
'Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83',
'Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36',
'Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11',
].join('\n'),
),
).toEqual(13);
});

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

describe('part2', () => {
it('should work for part 2 examples', () => {
expect(
part2(
[
'Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53',
'Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19',
'Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1',
'Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83',
'Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36',
'Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11',
].join('\n'),
),
).toEqual(30);
});

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

0 comments on commit ef5bf47

Please sign in to comment.