ภาพรวม
บทความนี้สาธิตวิธีตรวจสอบว่าอาร์เรย์สองชุดรวมกันแล้วจัดเรียงได้เป็นลำดับต่อเนื่อง (Consecutive Sequence) หรือไม่
ตัวอย่าง
arr1 = [4, 6, 2, 9, 3]
arr2 = [1, 5, 8, 7]
Combined: [1, 2, 3, 4, 5, 6, 7, 8, 9] -> Consecutive! -> true
การนำไปใช้ (มี Bug: Common Difference Logic)
const canFormSequence = (arr1, arr2) => {
const combined = [...arr1, ...arr2];
if (combined.length < 2) return true;
combined.sort((a, b) => a - b);
const commonDifference = combined[0] - combined[1]; // Bug: Should be combined[1] - combined[0]
for (let i = 1; i < combined.length - 1; i++) {
if (combined[i] - combined[i+1] === commonDifference) {
continue;
}
return false;
}
return true;
};
ผลลัพธ์
true
วิธีที่ถูกต้องและง่ายกว่า
const canFormSequenceCorrect = (arr1, arr2) => {
const combined = [...arr1, ...arr2];
if (combined.length < 2) return true;
const set = new Set(combined);
// ต้องไม่มี Duplicate
if (set.size !== combined.length) return false;
const min = Math.min(...combined);
const max = Math.max(...combined);
// Consecutive ถ้า max - min + 1 === length
return max - min + 1 === combined.length;
};
การทดสอบ
console.log(canFormSequenceCorrect([4,6,2,9,3], [1,5,8,7])); // true
console.log(canFormSequenceCorrect([1,2,4], [5,6])); // false (ขาด 3)
console.log(canFormSequenceCorrect([1,2,2], [3])); // false (Duplicate)
console.log(canFormSequenceCorrect([10], [11,12])); // true
Complexity
- Sort Version: O(n log n) Time, O(n) Space
- Set + Min/Max: O(n) Time, O(n) Space
- Boolean Array (Range Small): O(n) Time, O(range) Space
การประยุกต์ใช้
- Data Validation: ตรวจสอบ Sequence Completeness
- Card Games: Straight Flush Detection
- Database: Gap Analysis
- Puzzle Validation: Sudoku, KenKen