Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 2df8bd9

Browse filesBrowse files
committed
completed day 4
1 parent ddcb647 commit 2df8bd9
Copy full SHA for 2df8bd9

File tree

Expand file treeCollapse file tree

3 files changed

+245
-0
lines changed
Filter options
Expand file treeCollapse file tree

3 files changed

+245
-0
lines changed

‎day4/index.js

Copy file name to clipboard
+38Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { isNumeric } from "../helper.js";
2+
3+
export const part1 = ({ input }) => {
4+
let result = 0;
5+
input.forEach((row) => {
6+
const { have, winning } = getNumbers({ row });
7+
const matches = winning.filter((n) => have.includes(n));
8+
result += matches.length > 0 ? Math.pow(2, matches.length - 1) : 0;
9+
});
10+
return result;
11+
};
12+
13+
export const part2 = ({ input }) => {
14+
let result = 0;
15+
let cards = Array(input.length).fill(1);
16+
17+
for (let i = 0; i < input.length; i++) {
18+
const { have, winning } = getNumbers({ row: input[i] });
19+
const matches = winning.filter((n) => have.includes(n));
20+
21+
if (matches.length > 0) {
22+
for (let j = 1; j <= matches.length; j++) {
23+
if (cards[i + j]) cards[i + j] += cards[i];
24+
}
25+
}
26+
}
27+
result = cards.reduce((a, b) => a + b, 0);
28+
29+
return result;
30+
};
31+
32+
const getNumbers = ({ row }) => {
33+
const split = row.split(": ");
34+
const numbers = split[1].split(" | ");
35+
const winning = numbers[0].split(" ").filter((n) => isNumeric(n));
36+
const have = numbers[1].split(" ").filter((n) => isNumeric(n));
37+
return { winning, have };
38+
};

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.