-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathpart-two.js
77 lines (60 loc) · 2.37 KB
/
part-two.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const SEARCH_FOR = require('./input');
class Recipes {
constructor(SEARCH_FOR, initial_recipes = [3, 7]) {
this.search_for = String(SEARCH_FOR);
this.substr_length = -1 * (this.search_for.length * 3);
this.recipes = initial_recipes.slice(0);
this.recipes_str = this.recipes.join('');
this.elf1 = 0;
this.elf2 = 1;
}
createNewRecipes() {
let elf1_value = this.recipes[this.elf1];
let elf2_value = this.recipes[this.elf2];
let new_recipes = elf1_value + elf2_value;
this.recipes_str += new_recipes;
if (new_recipes < 10) {
this.recipes.push(new_recipes);
} else {
new_recipes = String(new_recipes)
.split('')
.map(n => +n);
new_recipes.forEach(r => {
this.recipes.push(r);
});
}
this.recipes_str = this.recipes_str.substr(this.substr_length);
let elf1_new_index = (this.elf1 + elf1_value + 1) % this.recipes.length;
let elf2_new_index = (this.elf2 + elf2_value + 1) % this.recipes.length;
this.elf1 = elf1_new_index;
this.elf2 = elf2_new_index;
}
getLengthWhenSearchForIsFirstFound() {
while (this.recipes_str.indexOf(this.search_for) < 0) {
this.createNewRecipes();
if (this.recipes.length % 4463 === 0) {
process.stdout.write(this.recipes.length + '\r')
}
}
// Clear out the screen
console.log(String(this.recipes.length).split('').map(n => ' ').join('') + ' \n')
// Trim our recipes array to make sure the last items are our search_for string exactly
let last_confirmed = false;
do {
let last_nums = [];
for (let i = 0; i < this.search_for.length; i++) {
last_nums.unshift(this.recipes[this.recipes.length - 1 - i]);
}
last_confirmed = last_nums.join('') === this.search_for;
if (!last_confirmed) {
this.recipes.pop();
}
} while (!last_confirmed);
return this.recipes.length - this.search_for.length;
}
}
let recipes = new Recipes(SEARCH_FOR);
// let recipes = new Recipes(92510); // 18
// let recipes = new Recipes(59414); // 2018
let length = recipes.getLengthWhenSearchForIsFirstFound();
console.log(length);