Add 2024/day2/part2.js
This commit is contained in:
parent
6c0e9c3fb3
commit
62afe67478
|
@ -0,0 +1,31 @@
|
||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
var fs = require('fs');
|
||||||
|
var data = fs.readFileSync(process.argv[2],'utf8').split('\n').filter(i=>i).map(i=>i.split(' ').map(i=>parseInt(i)));
|
||||||
|
|
||||||
|
var safety_count = 0;
|
||||||
|
|
||||||
|
function listwithout(list,idx) {
|
||||||
|
return list.slice(0,idx).concat(list.slice(idx+1));
|
||||||
|
}
|
||||||
|
|
||||||
|
function isreportsafe(report,retry=true) {
|
||||||
|
var first = report.slice(0,-1);
|
||||||
|
var diffs = first.map((elem,idx)=>report[idx+1]-elem);
|
||||||
|
if(diffs[0]<0) { //Is negative
|
||||||
|
diffs = diffs.map(i=>-i); //Negate it
|
||||||
|
}
|
||||||
|
for(var idx=0;idx<diffs.length;++idx) {
|
||||||
|
if(diffs[idx]<1 || diffs[idx]>3) {
|
||||||
|
//return false; //We need to test removal
|
||||||
|
//If an improvement is made then it will be by removing one of the elements associated with this diff
|
||||||
|
if(retry) return isreportsafe(listwithout(report,idx-1),false) || isreportsafe(listwithout(report,idx),false) || isreportsafe(listwithout(report,idx+1),false);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
var safety_count = data.reduce((acc,report)=>acc+(isreportsafe(report)?1:0),0);
|
||||||
|
|
||||||
|
console.log('Result:',safety_count);
|
Loading…
Reference in New Issue