@@ -6,7 +6,6 @@ class Recipes {
66 this . head = null
77 this . tail = null
88 this . length = 0
9- this . tracker = ''
109 this . addFirst ( recipe )
1110 }
1211
@@ -16,7 +15,6 @@ class Recipes {
1615 newRecipe . prev = newRecipe
1716 this . head = newRecipe
1817 this . tail = newRecipe
19- this . tracker += recipe . toString ( )
2018 this . length ++
2119 return this
2220 }
@@ -32,7 +30,6 @@ class Recipes {
3230 newRecipe . prev = this . head // link new recipe to old head
3331 this . head . next = newRecipe
3432 this . head = newRecipe // make new recipe the new head
35- this . tracker += recipe . toString ( ) // Sore the sequence
3633 this . length ++
3734 return this . head
3835 }
@@ -65,8 +62,10 @@ const totalDigitsInArray = (arr) => {
6562 * @param {Numbe } repeat count of desired iterations
6663 */
6764const loopRecipesForElves = ( elves , recipes , repeat ) => {
65+ let result = ''
6866 for ( let x = 1 ; x <= repeat ; x ++ ) {
6967 const score = totalDigitsInArray ( elves . map ( ( elf ) => elf . value ) )
68+ result += score . toString ( )
7069 recipes . scoreRecipes ( score )
7170 elves . forEach ( ( elf , idx ) => {
7271 const distance = elf . value + 1
@@ -76,6 +75,7 @@ const loopRecipesForElves = (elves, recipes, repeat) => {
7675 elves [ idx ] = elf
7776 } )
7877 }
78+ return result
7979}
8080
8181/**
@@ -111,13 +111,20 @@ const calculateXAfterY = (x, y, recipes, elves) => {
111111 * @param {String } pattern to search for
112112 * @param {LinkedList } recipes recipe list
113113 * @param {Array } elves doing the work
114+ * @param {Number } bufferSize bucket size to search. Higher sizes use more memory but go faster
114115 */
115- const findPattern = ( pattern , recipes , elves ) => {
116- let position = - 1
117- // Generate the sequence until the sequence exists
118- while ( position < 0 ) {
119- loopRecipesForElves ( elves , recipes , 1 )
120- position = recipes . tracker . indexOf ( pattern )
116+ const findPattern = ( pattern , recipes , elves , bufferSize ) => {
117+ bufferSize = bufferSize || 10000
118+ let matched = false
119+ let position = recipes . length
120+ while ( matched !== true ) {
121+ let haystack = loopRecipesForElves ( elves , recipes , bufferSize )
122+ if ( haystack . indexOf ( pattern ) > - 1 ) {
123+ position += haystack . indexOf ( pattern )
124+ matched = true
125+ } else {
126+ position += 1000
127+ }
121128 }
122129 return position
123130}
0 commit comments