Published
Edited
Dec 3, 2020
Insert cell
Insert cell
Insert cell
parsePolicy = p => {
const matches = p.match(/(\d+)-(\d+) (\w)/);
if (! matches ) throw p;
return {
min: parseInt( matches[1] ),
max: parseInt( matches[2] ),
char: matches[3]
}
}
Insert cell
parseInput = ( i ) => i.split('\n')
.map( l => l.split(': ') )
.map( ( [policySpec, password] ) => [ parsePolicy(policySpec), password] )
Insert cell
parseInput(testInput);
Insert cell
validatePassword = ( [ policy, password ] ) => {
let count = 0;
for ( let i = 0; i < password.length; i++ ) {
if ( password[i] === policy.char ) count++;
if ( count > policy.max ) return false;
}
if ( count < policy.min ) return false;
return true;
}
Insert cell
parseInput(testInput).filter(validatePassword)
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
xor = (a, b) => (a && !b) || (!a && b)
Insert cell
validatePassword2 = ( [ policy, password ] ) => {
const char1 = password[ policy.min - 1 ],
char2 = password[ policy.max - 1 ];
// throw JSON.stringify({ password, char1, char2, policy });
return xor( char1 === policy.char, char2 === policy.char );
}
Insert cell
parseInput(testInput).filter(validatePassword2)
Insert cell
parseInput(input).filter(validatePassword2).length
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more