Restructure folders and add day 3's solution
This commit is contained in:
parent
ecab4f263a
commit
519c1b63cc
6 changed files with 123 additions and 1 deletions
51
javascript/day_02/part2.mjs
Normal file
51
javascript/day_02/part2.mjs
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { readFile } from "fs/promises";
|
||||
|
||||
if (process.argv.length <= 3) {
|
||||
console.error(`Needs more args >:(`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const fileToRead = process.argv[2];
|
||||
const gap = parseInt(process.argv[3])
|
||||
const file = await readFile(fileToRead, `utf-8`);
|
||||
|
||||
let validLines = 0;
|
||||
for (const line of file.split(`\n`)) {
|
||||
// console.log(line)
|
||||
const ints = line.split(` `)
|
||||
.map(v => Number.parseInt(v))
|
||||
// .reverse()
|
||||
|
||||
let isValid = true;
|
||||
let errorCorrected = false;
|
||||
let firstSign = null;
|
||||
let firstIter = true;
|
||||
for (var i = 0; i < ints.length - 1; i++) {
|
||||
const a = ints[i];
|
||||
const b = ints[i + 1];
|
||||
|
||||
const sign = Math.sign( a - b );
|
||||
const delta = Math.abs( a - b );
|
||||
|
||||
firstSign ??= sign;
|
||||
|
||||
const rightDirection = sign === firstSign;
|
||||
const deltaWithinRange = delta <= gap;
|
||||
|
||||
if (!rightDirection || !deltaWithinRange) {
|
||||
isValid &&= !errorCorrected;
|
||||
if (!isValid) {
|
||||
break;
|
||||
}
|
||||
errorCorrected = true;
|
||||
ints.splice(i , 1);
|
||||
i--;
|
||||
continue;
|
||||
}
|
||||
firstIter = false;
|
||||
};
|
||||
console.log({ firstSign, isValid, errorCorrected, ints })
|
||||
if (isValid) validLines++;
|
||||
};
|
||||
|
||||
console.log(`Number of valid reports:`, validLines);
|
||||
Loading…
Add table
Add a link
Reference in a new issue