File tree 1 file changed +63
-0
lines changed
1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* ---------------------- Day 1: Sonar Sweep ------------------------ */
2
+ const fs = require ( "fs" ) ;
3
+
4
+ function countIncreasedMeasurements ( measurements ) {
5
+ let count = 0 ;
6
+
7
+ for ( let i = 1 ; i < measurements . length ; i ++ ) {
8
+ if ( measurements [ i ] > measurements [ i - 1 ] ) {
9
+ count ++ ;
10
+ }
11
+ }
12
+
13
+ return count ;
14
+ }
15
+
16
+ function countIncreasesSlidingWindow ( measurements , windowSize ) {
17
+ let count = 0 ,
18
+ currSum = 0n ,
19
+ prevSum = 0n ;
20
+
21
+ for ( let i = 0 ; i < windowSize ; i ++ ) {
22
+ prevSum += BigInt ( measurements [ i ] ) ;
23
+ }
24
+
25
+ console . log ( prevSum ) ;
26
+ for ( let i = windowSize ; i < measurements . length ; i ++ ) {
27
+ // add next number to currSum and then subtract the first number from previous window
28
+ currSum = prevSum + BigInt ( measurements [ i ] ) - BigInt ( measurements [ i - windowSize ] ) ;
29
+
30
+ if ( currSum > prevSum ) {
31
+ count ++ ;
32
+ }
33
+
34
+ prevSum = currSum ;
35
+ }
36
+
37
+ return count ;
38
+ }
39
+
40
+ function getInput ( fileName ) {
41
+ try {
42
+ const data = fs . readFileSync ( fileName , "utf8" ) ;
43
+ return data ;
44
+ } catch ( err ) {
45
+ console . error ( err ) ;
46
+ }
47
+ }
48
+
49
+ module . exports = {
50
+ dayOnePart1 : ( ) => {
51
+ const inputs = getInput ( "inputs/day1-inputs.txt" ) ;
52
+ let inputsArr = inputs . split ( "\n" ) . map ( ( element ) => parseInt ( element ) ) ;
53
+
54
+ return countIncreasedMeasurements ( inputsArr ) ;
55
+ } ,
56
+
57
+ dayOnePart2 : ( ) => {
58
+ const inputs = getInput ( "inputs/day1-inputs.txt" ) ;
59
+ let inputsArr = inputs . split ( "\n" ) . map ( ( element ) => parseInt ( element ) ) ;
60
+
61
+ return countIncreasesSlidingWindow ( inputsArr , 3 ) ;
62
+ } ,
63
+ } ;
You can’t perform that action at this time.
0 commit comments