File tree Expand file tree Collapse file tree 3 files changed +245
-0
lines changed
Filter options
Expand file tree Collapse file tree 3 files changed +245
-0
lines changed
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments