Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const checkBadReport = (report: number[], currentReport: number) => {
- const trendScore = report.reduce<number>((acc, num, i, arr) => {
- if (i < arr.length - 1) {
- acc += arr[i + 1] > arr[i] ? 1 : arr[i + 1] < arr[i] ? -1 : 0
- }
- return acc
- }, 0)
- const isDecreasingTrend = trendScore < 0
- const isIncreasingTrend = !isDecreasingTrend
- const isDecreasing = (i: number, j: number) => report[j] < report[i]
- const isIncreasing = (i: number, j: number) => report[j] > report[i]
- const diff = report.length - Math.abs(trendScore)
- if (trendScore === 0 || diff > 3) return false
- let removedIndex = -1
- for (let i = 0; i < report.length - 1; i++) {
- if (isDecreasingTrend) {
- if (!isDecreasing(i, i + 1)) {
- if (removedIndex !== -1) return false
- if (i > 0 ? isDecreasing(i - 1, i + 1) : true) {
- removedIndex = i
- }
- }
- } else if (isIncreasingTrend) {
- if (!isIncreasing(i, i + 1)) {
- if (removedIndex !== -1) return false
- if (i > 0 ? isIncreasing(i - 1, i + 1) : true) {
- removedIndex = i
- }
- }
- }
- }
- if (removedIndex !== -1) {
- report.splice(removedIndex)
- }
- // Now the report is stricty increasing or decreasing
- // if(!(JSON.stringify(report.sort((a, b) => a - b)) === JSON.stringify(report) || JSON.stringify(report.sort((a, b) => b - a)) === JSON.stringify(report))) {
- // console.log(report)
- // }
- for (let i = 0; i < report.length - 1; i++) {
- const checkCondition = (i: number, j: number) => Math.abs(report[i] - report[j]) >= 1 && Math.abs(report[i] - report[j]) <= 3
- if(!checkCondition(i, i + 1)) {
- if(removedIndex !== -1) return false
- // either remove i or i + 1
- if(i > 0 && i < report.length - 1) {
- if(checkCondition(i - 1, i + 1)) removedIndex = i
- } else removedIndex = i
- }
- }
- return true
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement