Advertisement
_joel1024

Untitled

Dec 2nd, 2024
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const checkBadReport = (report: number[], currentReport: number) => {
  2.     const trendScore = report.reduce<number>((acc, num, i, arr) => {
  3.         if (i < arr.length - 1) {
  4.             acc += arr[i + 1] > arr[i] ? 1 : arr[i + 1] < arr[i] ? -1 : 0
  5.         }
  6.         return acc
  7.     }, 0)
  8.  
  9.     const isDecreasingTrend = trendScore < 0
  10.     const isIncreasingTrend = !isDecreasingTrend
  11.  
  12.     const isDecreasing = (i: number, j: number) => report[j] < report[i]
  13.     const isIncreasing = (i: number, j: number) => report[j] > report[i]
  14.  
  15.     const diff = report.length - Math.abs(trendScore)
  16.  
  17.     if (trendScore === 0 || diff > 3) return false
  18.  
  19.     let removedIndex = -1
  20.     for (let i = 0; i < report.length - 1; i++) {
  21.         if (isDecreasingTrend) {
  22.             if (!isDecreasing(i, i + 1)) {
  23.                 if (removedIndex !== -1) return false
  24.  
  25.                 if (i > 0 ? isDecreasing(i - 1, i + 1) : true) {
  26.                     removedIndex = i
  27.                 }
  28.             }
  29.         } else if (isIncreasingTrend) {
  30.             if (!isIncreasing(i, i + 1)) {
  31.                 if (removedIndex !== -1) return false
  32.  
  33.                 if (i > 0 ? isIncreasing(i - 1, i + 1) : true) {
  34.                     removedIndex = i
  35.                 }
  36.             }
  37.         }
  38.     }
  39.  
  40.     if (removedIndex !== -1) {
  41.         report.splice(removedIndex)
  42.     }
  43.  
  44.     // Now the report is stricty increasing or decreasing    
  45.     // if(!(JSON.stringify(report.sort((a, b) => a - b)) === JSON.stringify(report) || JSON.stringify(report.sort((a, b) => b - a)) === JSON.stringify(report))) {
  46.     //     console.log(report)
  47.     // }
  48.  
  49.     for (let i = 0; i < report.length - 1; i++) {
  50.         const checkCondition = (i: number, j: number) => Math.abs(report[i] - report[j]) >= 1 && Math.abs(report[i] - report[j]) <= 3
  51.  
  52.         if(!checkCondition(i, i + 1)) {
  53.             if(removedIndex !== -1) return false
  54.             // either remove i or i + 1
  55.             if(i > 0 && i < report.length - 1) {
  56.                 if(checkCondition(i - 1, i + 1)) removedIndex = i
  57.             } else removedIndex = i
  58.         }
  59.     }
  60.  
  61.     return true
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement