ภาพรวม
บทความนี้สาธิตวิธีนับจำนวนกลุ่ม (Clusters) ของตัวเลข Non-negative (>=0) ที่ติดต่อกันในอาร์เรย์
ตัวอย่าง
Input: [-1,-2,-1,0,-1,-2,-1,-2,-1,0,1,0]
Groups: [0] at index 3, [0,1,0] at index 9-11
Output: 2
การนำไปใช้
const positiveClusters = (arr) => {
return arr.reduce((acc, val, ind) => {
// จบกลุ่มเมื่อ: ค่าปัจจุบัน >= 0 และ (ค่าถัดไป < 0 หรือเป็นตัวสุดท้าย)
if (val >= 0 && (arr[ind + 1] < 0 || ind + 1 === arr.length)) {
acc++;
}
return acc;
}, 0);
};
console.log(positiveClusters([-1,-2,-1,0,-1,-2,-1,-2,-1,0,1,0])); // 2
ผลลัพธ์
2
วิธีการที่อ่านง่ายกว่า
const countPositiveClusters = (arr) => {
let count = 0;
let inCluster = false;
for (const val of arr) {
if (val >= 0) {
if (!inCluster) {
count++;
inCluster = true;
}
} else {
inCluster = false;
}
}
return count;
};
การขยาย: นับ Negative Clusters ด้วย
const countSignClusters = (arr) => {
let posClusters = 0, negClusters = 0;
let inPos = false, inNeg = false;
for (const val of arr) {
if (val > 0) {
if (!inPos) { posClusters++; inPos = true; }
inNeg = false;
} else if (val < 0) {
if (!inNeg) { negClusters++; inNeg = true; }
inPos = false;
} else { // val === 0
if (!inPos) { posClusters++; inPos = true; }
inNeg = false;
}
}
return { positive: posClusters, negative: negClusters };
};
การประยุกต์ใช้
- Signal Processing: Detect Positive/Negative Runs
- Financial: Winning/Losing Streaks
- Quality Control: Defect Clusters
- Time Series: Regime Detection
- Image Processing: Run-Length Encoding
Generic Cluster Counter
const countClusters = (arr, predicate) => {
let count = 0;
let inCluster = false;
for (const val of arr) {
const matches = predicate(val);
if (matches && !inCluster) {
count++;
inCluster = true;
} else if (!matches) {
inCluster = false;
}
}
return count;
};
// ใช้งาน
const positiveClusters = arr => countClusters(arr, x => x >= 0);
const negativeClusters = arr => countClusters(arr, x => x < 0);
const zeroClusters = arr => countClusters(arr, x => x === 0);