Advertisement
_joel1024

Untitled

Dec 2nd, 2024
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { parser } from "./sol1";
  2.  
  3. const reports = parser("input.txt");
  4.  
  5. const checkBadReport = (report: number[]) => {
  6.     const freqMap: Record<string, number[]> = {}
  7.  
  8.     const getProps = (i: number, j: number) => {
  9.         const equality = report[i] < report[j] ? "increasing": report[i] > report[j] ? "decreasing": "equal"
  10.         const valid = Math.abs(report[i] - report[j]) >= 1 && Math.abs(report[i] - report[j]) <= 3
  11.  
  12.         return [valid, equality] as [boolean, string]
  13.     }
  14.  
  15.     for (let i = 0; i < report.length - 1; i++) {
  16.         const props = JSON.stringify(getProps(i, i + 1))
  17.         if (!(props in freqMap)) freqMap[props] = []
  18.         freqMap[props].push(i)
  19.     }
  20.  
  21.     if (Object.keys(freqMap).length < 2) return JSON.parse(Object.keys(freqMap)[0])[0]
  22.     if (Object.keys(freqMap).length > 2) return false
  23.    
  24.  
  25.     for (let props in freqMap) {
  26.         if (freqMap[props].length === 1) {
  27.             const otherProp = Object.keys(freqMap).find(k => k !== props)!
  28.             const i = freqMap[props][0]
  29.             const condition = (i: number) => (i <= 0 || i >= report.length - 1 || JSON.stringify(getProps(i - 1, i + 1)) === otherProp)
  30.             if (condition(i) || condition(i + 1)) {
  31.                 return JSON.parse(otherProp)[0]
  32.             }
  33.         }
  34.     }
  35.  
  36.     return false
  37. }
  38.  
  39. const ans = reports.reduce<number>((ans, report) => {
  40.     return checkBadReport(report) ? ans += 1 : ans
  41. }, 0);
  42.  
  43. console.log(ans);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement