type InputData ={
reports: Array<Array<number>>,
};
const solution: Fn = async ({ reports }) => {
let count = 0;
for (let i = 0; i < reports.length; i++) {
await checkSafety(reports[i])
.then(() => count++)
.catch(() => {});
}
return count;
};
const checkSafety: CheckFn = async (report) => {
const promise = new Promise<boolean>(async (resolve, reject) => {
setTimeout(() => {
const first = report[0];
const second = report[1];
const isAscending = first < second;
let isReportSafe = true;
for (let j = 0; j < report.length - 1; j++) {
const level = report[j];
const nextLevel = report[j + 1];
const diff = Math.abs(level - nextLevel);
if (diff === 0 || diff > 3) {
isReportSafe = false;
break;
}
if (isAscending && level > nextLevel) {
isReportSafe = false;
break;
}
if (!isAscending && level < nextLevel) {
isReportSafe = false;
break;
}
}
if (isReportSafe) { resolve(true); }
else { reject(false); }
});
});
return promise;
};
const solution: Fn = async ({ reports }) => {
let count = 0;
for (let i = 0; i < reports.length; i++) {
let safe = 0;
const report = reports[i];
// check part 1 for checkSafety definition
const main = checkSafety(report)
.then(() => safe++)
.catch(() => {});
const tests = report.map((_, j) => {
const newReport = [...report];
newReport.splice(j, 1);
return checkSafety(newReport)
.then(() => safe++)
.catch(() => {});
});
await Promise.all([main, ...tests]);
if (safe > 0) { count++; }
}
return count;
};