@@ -6,7 +6,7 @@ export async function part1(inputFile: string): Promise<number> {
66}
77
88export async function part2 ( inputFile : string ) : Promise < number > {
9- return await day1 ( inputFile , countZeroPositions ) ;
9+ return await day1 ( inputFile , countZeroPassages ) ;
1010}
1111
1212type MovementType = { dir : string , value : number } ;
@@ -26,18 +26,38 @@ async function day1(inputFile: string, calcFn: ( movements: MovementType[]) => n
2626
2727
2828function countZeroPositions ( movements : MovementType [ ] ) : number {
29- let zeroPassages = 0 ;
29+ let positionsOnZero = 0 ;
3030 let position = 50 ;
3131
3232 movements . forEach ( movement => {
3333 const newPosition = movement . dir === 'R' ? position + movement . value : position - movement . value ;
3434 position = ( ( newPosition % 100 ) + 100 ) % 100 ; // handles all cases: positive, negative, multiple wraps
3535
3636 if ( position === 0 ) {
37- zeroPassages ++ ;
37+ positionsOnZero ++ ;
3838 }
3939 } )
4040
41- return zeroPassages ;
41+ return positionsOnZero ;
4242}
4343
44+ function countZeroPassages ( movements : MovementType [ ] ) : number {
45+ let count = 0 ;
46+ let position = 50 ;
47+
48+ movements . forEach ( ( { dir, value } ) => {
49+ // firstK: the number of clicks until we first land on 0
50+ // If position == 0 we already left it, so next landing is after a full circle
51+ if ( dir === 'R' ) {
52+ const firstK = position === 0 ? 100 : 100 - position ;
53+ if ( value >= firstK ) count += Math . floor ( ( value - firstK ) / 100 ) + 1 ;
54+ position = ( position + value ) % 100 ;
55+ } else {
56+ const firstK = position === 0 ? 100 : position ;
57+ if ( value >= firstK ) count += Math . floor ( ( value - firstK ) / 100 ) + 1 ;
58+ position = ( ( position - value ) % 100 + 100 ) % 100 ;
59+ }
60+ } ) ;
61+
62+ return count ;
63+ }
0 commit comments