First we have to process our input and extract the useful info. We split line by line to get each password on it's own and iterate through all our lines. For each line we then use some string splitting and array destructuring to get the valuable information into properly named variables. We want to extract the two integers (as lower and upper bounds), the main character we will be testing against, and the actuall password string each into their own named variables.
Then we check through each character of the main password string, counting the number that match our test char. If that count falls within our lower and upper bounds we have found a valid password and can add it to our numValid running total.
const fs = require('fs');
const input = fs.readFileSync('day2/node/input.txt', "utf8").split('\n').map(el => el.split(' '));
let numValid = 0;
for(line of input){
const [rule, char, password] = line;
const [lowerbound, upperbound] = rule.split('-');
const counterChar = char[0];
let count = 0;
for(character of password.split('')){
if(character === counterChar){
++count;
}
}
if( lowerbound <= count && count <= upperbound){
++numValid;
}
}
console.log(numValid);