This is day 2 of the Advent of Code challenge. Here is my solution and the identifier
function is different between part 1 and 2:
const items = document
.querySelector("body > pre:nth-child(1)")
.innerText.split("\n");
items.pop();
// part 1
const identifier = (str, char, min, max) => {
const re = RegExp(`${char}`, "g");
const count = (str.match(re) || []).length;
if (min <= count && count <= max) {
return 1;
} else {
return 0;
}
};
// part 2
const identifier = (str, char, min, max) => {
const re = RegExp(`${char}`, "g");
const firstPos = str[min - 1] === char ? 1 : 0;
const secondPos = str[max - 1] === char ? 1 : 0;
const count = firstPos + secondPos;
if (count === 1) {
return 1;
} else {
return 0;
}
};
let count = 0;
items.forEach((item) => {
const config = item.split(" ");
const str = config[2];
const char = config[1].replace(":", "");
const min = config[0].split("-")[0];
const max = config[0].split("-")[1];
count += identifier(str, char, min, max);
});
console.log(count);
Some thoughts when solving the problem:
- A lot of the problems can be solved by breaking it down piece by piece
Top comments (0)