Skip to content

Instantly share code, notes, and snippets.

@freddan88
Created November 18, 2020 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save freddan88/e56f2daa68e7a31953957319d1524ba1 to your computer and use it in GitHub Desktop.
Save freddan88/e56f2daa68e7a31953957319d1524ba1 to your computer and use it in GitHub Desktop.
Node.js solution
const fs = require("fs");
const puzzleInput = "172851-675869";
const RANGE = puzzleInput.split("-");
const LOWER = RANGE[0].length === 6 ? parseInt(RANGE[0]) : 0;
const HIGHER = RANGE[1].length === 6 ? parseInt(RANGE[1]) : 0;
if (!LOWER || !HIGHER) return;
let possiblePasswords = [];
if (fs.existsSync("./passwords.txt")) {
fs.unlinkSync("./passwords.txt");
}
const checkAscending = (password) => {
for (let index = 0; index < 5; index++) {
if (password[index] > password[index + 1]) return false;
}
return true;
};
const checkAdjacent = (password) => {
for (let index = 0; index < 5; index++) {
const regex = new RegExp(`${password[index]}{2}`, "g");
if (regex.test(password)) return true;
}
return false;
};
for (let number = LOWER; number <= HIGHER; number++) {
if (checkAscending(number.toString())) {
if (checkAdjacent(number.toString())) {
possiblePasswords.push(number);
fs.writeFileSync("passwords.txt", number + "\r\n", {
encoding: "utf8",
flag: "a+",
mode: 0o666,
});
}
}
}
const fulfills = possiblePasswords.length;
console.log("");
console.log(
`There are ${fulfills} different passwords in range ${puzzleInput} meeting the criteria`
);
console.log("Se file: ./passwords.txt");
console.log("");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment