day 2, change filter/count to reduce

This commit is contained in:
Joshua Seigler 2020-12-02 21:30:58 +00:00
parent 6eeaabc649
commit 170e72f666

View file

@ -20,30 +20,41 @@ async function run () {
} }
async function solveForFirstStar (input) { async function solveForFirstStar (input) {
const solution = input.filter( const solution = input.reduce(
({ num1, num2, letter, password }) => { (acc, { num1, num2, letter, password }) => {
let count = 0 let count = 0
for (let i = 0; i < password.length; i++) { for (let i = 0; i < password.length; i++) {
if (password.charAt(i) === letter) { if (password.charAt(i) === letter) {
count++ count++
if (count > num2) { if (count > num2) {
return false return acc
} }
} }
} }
return count >= num1 return acc + (
} count >= num1
).length ? 1
: 0
)
}, 0
)
report('Input:', input) report('Input:', input)
report('Solution 1:', solution) report('Solution 1:', solution)
} }
async function solveForSecondStar (input) { async function solveForSecondStar (input) {
const solution = input.filter( const solution = input.reduce(
({ num1, num2, letter, password }) => { (acc, { num1, num2, letter, password }) => {
return XOR(password.charAt(num1 - 1) === letter, password.charAt(num2 - 1) === letter) return acc + (
} XOR(
).length password.charAt(num1 - 1) === letter,
password.charAt(num2 - 1) === letter
)
? 1
: 0
)
}, 0
)
report('Solution 2:', solution) report('Solution 2:', solution)
} }