Javascript solution:
let fs = require("fs"); var entryList = fs.readFileSync("input.txt", "utf8").split("\n"); function checkCharacter(str, chr, min, max) { let count = 0; for (let c of str) { if (c == chr) { count++; } } return !(count < min || count > max); } let validPasswords = 0; for (let entry of entryList) { let patterns = entry.split(": "); let validatorPattern = patterns[0].split(" "); let minMax = validatorPattern[0].split("-"); if ( checkCharacter( patterns[1], validatorPattern[1], parseInt(minMax[0]), parseInt(minMax[1]) ) ) { validPasswords++; } } console.log("Part one"); console.log("Valid passwords: ", validPasswords); function isValidPassword(str, chr, validPos, invalidPos) { return ( (str.charAt(validPos) === chr || str.charAt(invalidPos) === chr) && str.charAt(validPos) != str.charAt(invalidPos) ); } validPasswords = 0; for (let entry of entryList) { let patterns = entry.split(": "); let validatorPattern = patterns[0].split(" "); let validInvalid = validatorPattern[0].split("-"); if ( isValidPassword( patterns[1], validatorPattern[1], parseInt(validInvalid[0]) - 1, parseInt(validInvalid[1]) - 1 ) ) { validPasswords++; } } console.log("Part two"); console.log("Valid passwords: ", validPasswords);
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Javascript solution: