ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ของตัวเลข arr เป็นอาร์กิวเมนต์เดียว
ฟังก์ชันควรตรวจสอบว่าอาร์เรย์อินพุตเป็น centrally peaked array หรือไม่ ถ้าใช่คืน true มิฉะนั้น false
เงื่อนไขในการเป็น centrally peaked array คือ:
arr.length >= 3
มี i อยู่ที่ 0 < i < arr.length - 1 ที่ทำให้:
arr[0] < arr[1] < ... arr[i-1] < arr[i]
arr[i] > arr[i+1] > ... > arr[arr.length - 1]
ตัวอย่างเช่น หากอินพุตคือ
const arr = [2, 6, 7, 9, 5, 3, 1];
ผลลัพธ์ควรเป็น
const output = true;
คำอธิบายผลลัพธ์
เพราะอาร์เรย์มีจุดสูงสุดที่ 9
ตัวอย่างโค้ด
const arr = [2, 6, 7, 9, 5, 3, 1];
const isCentrallyPeaked = (arr = []) => {
let ind = undefined;
for (let i = 1; i <= arr.length - 1; i++) {
if (ind === undefined) {
if (arr[i] < arr[i - 1]) {
ind = i - 1;
} else if (arr[i] === arr[i - 1]) {
return false;
}
} else if (arr[i] >= arr[i - 1]) {
return false;
}
}
return ind > 0 && ind < arr.length - 1;
};
console.log(isCentrallyPeaked(arr));ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็น
true