-
Notifications
You must be signed in to change notification settings - Fork 0
/
day7.js
111 lines (88 loc) · 2.64 KB
/
day7.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
const fs = require('fs')
fs.readFile('./input_day7.txt', 'utf8' , (err, data) => {
if (err) {
console.error(err)
return err;
}
calculateBags(data)
calculateIncludingBags(data)
})
function calculateBags(input) {
data = input.split("\n");
let searchList = ["shiny gold"];
let resultList = ["shiny gold"];
let colourList = [];
while (true) {
searchList = resultList;
resultList = [];
data.forEach((row, i) => {
searchList.forEach((colour, j) => {
if (row.includes(colour) && row.substring(0, colour.length) !== colour) {
resultList.push(row.split("bags")[0]);
colourList.push(row.split("bags")[0])
}
});
});
if (resultList.length === 0) {
break;
}
}
colourList.sort();
for (var j = 0; j < colourList.length - 1; j++) {
if (colourList[j] === colourList[j+1]) {
colourList.splice(j, 1);
j--;
}
}
console.log(colourList.length);
}
function calculateIncludingBags(input) {
data = input.split("\n");
let colourList = [];
let resultList = ["shiny gold"];
let baglist = [];
let noOfBags = 0;
let path = "shiny gold bags contain 1 pale maroon bag, 3 plaid blue bags, 5 dull tan bags."
let stillReplacing = true;
while (stillReplacing) {
stillReplacing = false;
data.forEach((row, i) => {
let rowColour = row.split("contain")[0].split(" bags")[0];
if (path.includes(rowColour) && rowColour !== "shiny gold" && rowColour !== "") {
let toReplace = row.split("contain")[1];
toReplace = "(".concat(toReplace).concat(")");
console.log(path);
console.log("To replace", toReplace);
if (toReplace !== undefined && toReplace !== "( no other bags.)") {
path = path.replace(rowColour, toReplace);
stillReplacing = true;
}
}
});
console.log(path);
}
while (path.includes("bags,") || path.includes("bag,") || path.includes("bags.") || path.includes("bag.")) {
path = path.replace("bags,", "+");
path = path.replace("bag,", "+");
path = path.replace("bags.", "");
path = path.replace("bag.", "");
}
console.log(path);
let pathArray = path.split("");
for (var i = 0; i < pathArray.length; i++) {
if (isNaN(parseInt(pathArray[i])) && pathArray[i] !== "(" && pathArray[i] !== ")" && pathArray[i] !== "+") {
// pathArray[]
pathArray.splice(i,1);
i--;
} else if (pathArray[i] === "(") {
pathArray[i] = "*("
} else if (pathArray[i] === ")") {
pathArray[i] = "+1)";
}
}
path = pathArray.join();
while (path.includes(",")) {
path = path.replace(",", "");
}
console.log(path);
}