1+ import { readFileFromCurrentDirectory } from '../utils/readFile.js' ;
2+
3+ const content = readFileFromCurrentDirectory ( ) ;
4+
5+ const leftValues : number [ ] = [ ] ;
6+ const rightValues : number [ ] = [ ] ;
7+
8+ // Split the content into lines
9+ const lines = content . trim ( ) . split ( "\n" ) ;
10+
11+ // Process each line and split into columns
12+ lines . forEach ( line => {
13+ const [ left , right ] = line
14+ . trim ( )
15+ . split ( / \s + / )
16+ . map ( Number ) ; // Split by spaces or tabs and convert to numbers
17+
18+ leftValues . push ( left ) ;
19+ rightValues . push ( right ) ;
20+ } ) ;
21+
22+ // Sort arrays in ascending order
23+ leftValues . sort ( ( a , b ) => a - b ) ;
24+ rightValues . sort ( ( a , b ) => a - b ) ;
25+
26+ // Calculate distance between the values
27+ const distance = leftValues . reduce ( ( sum , left , index ) => {
28+ return sum + Math . abs ( left - rightValues [ index ] ) ;
29+ } , 0 ) ;
30+
31+ console . log ( "Part 1: " + distance ) ;
32+
33+ // Calculate similarity score
34+ let similarityScore = 0 ;
35+
36+ for ( const leftValue of leftValues ) {
37+ // Count how many times the left value appears in right list
38+ const appearanceInRight = rightValues . filter ( rightValue => rightValue === leftValue ) . length ;
39+
40+ // Calculate similarity score
41+ similarityScore += ( leftValue * appearanceInRight ) ;
42+ }
43+
44+ console . log ( "Part 2: " + similarityScore ) ;
0 commit comments