@@ -38,13 +38,18 @@ class Head extends Point {
38
38
class Tail extends Point {
39
39
history : string [ ] = [ ]
40
40
head : Point
41
- constructor ( x : number , y : number , head : Point ) {
41
+ withHistory : boolean
42
+ constructor ( x : number , y : number , head : Point , withHistory = false ) {
42
43
super ( x , y )
43
44
this . head = head
45
+ this . withHistory = withHistory
44
46
this . addToHistory ( this . x , this . y )
45
47
}
46
48
47
49
addToHistory = ( x : number , y : number ) => {
50
+ if ( ! this . withHistory ) {
51
+ return
52
+ }
48
53
const key = x + "_" + y
49
54
if ( this . history . includes ( key ) ) {
50
55
return
@@ -53,6 +58,9 @@ class Tail extends Point {
53
58
}
54
59
55
60
addToHistoryRange = ( a1 : number , a2 : number , b : number , xrange : boolean ) => {
61
+ if ( ! this . withHistory ) {
62
+ return
63
+ }
56
64
const diff = a2 - a1
57
65
const step = Math . sign ( diff )
58
66
let i = a1
@@ -77,11 +85,8 @@ class Tail extends Point {
77
85
const diffY = this . head . y - y
78
86
const diffX = this . head . x - x
79
87
80
- if ( Math . abs ( diffX ) === 1 && diffY === 0
81
- || Math . abs ( diffY ) === 1 && diffX === 0
82
- || diffX === 0 && diffY === 0
83
- || Math . abs ( diffX ) === 1 && Math . abs ( diffY ) === 1 ) {
84
- break
88
+ if ( ( diffX === 0 || Math . abs ( diffX ) === 1 ) && ( diffY === 0 || Math . abs ( diffY ) === 1 ) ) {
89
+ break ;
85
90
}
86
91
if ( diffY === 0 ) {
87
92
const tmp = x
@@ -119,7 +124,7 @@ class Solve09 extends FileReader {
119
124
120
125
process1 = ( data : string [ ] ) => {
121
126
const head = new Head ( 0 , 0 )
122
- const tail = new Tail ( 0 , 0 , head )
127
+ const tail = new Tail ( 0 , 0 , head , true )
123
128
data . forEach ( row => {
124
129
const data = row . split ( ' ' ) ;
125
130
head . move ( data [ 0 ] as Dir , parseInt ( data [ 1 ] , 10 ) )
@@ -134,15 +139,19 @@ class Solve09 extends FileReader {
134
139
const size = 9
135
140
let last : Point = head
136
141
for ( let i = 0 ; i < size ; i ++ ) {
137
- const tail = new Tail ( 0 , 0 , last )
142
+ const tail = new Tail ( 0 , 0 , last , i === size - 1 )
138
143
tails . push ( tail )
139
144
last = tail
140
145
}
141
146
142
147
data . forEach ( row => {
143
148
const data = row . split ( ' ' ) ;
144
- head . move ( data [ 0 ] as Dir , parseInt ( data [ 1 ] , 10 ) )
145
- tails . forEach ( t => t . moveToHead ( ) )
149
+ const moves = parseInt ( data [ 1 ] , 10 )
150
+ const dir = data [ 0 ] as Dir
151
+ for ( let i = 0 ; i < moves ; i ++ ) {
152
+ head . move ( dir , 1 )
153
+ tails . forEach ( t => t . moveToHead ( ) )
154
+ }
146
155
} )
147
156
console . log ( ( last as Tail ) . history . length )
148
157
} ;
0 commit comments