Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การตรวจสอบว่าสองอาร์เรย์รวมกันได้ลำดับต่อเนื่อง - JavaScript

ตรวจสอบว่าสองอาร์เรย์รวมกันแล้วจัดเรียงใหม่ได้ลำดับตัวเลขต่อเนื่อง (consecutive sequence) หรือไม่

ตัวอย่าง

arr1 = [4, 6, 2, 9, 3]
arr2 = [1, 5, 8, 7]
// รวม: [1,2,3,4,5,6,7,8,9] → consecutive → true

ตัวอย่างโค้ด

const arr1 = [4, 6, 2, 9, 3];
const arr2 = [1, 5, 8, 7];

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];

  for (let i = 1; i < combined.length - 1; i++) {
    if (combined[i] - combined[i + 1] === commonDifference) {
      continue;
    }
    return false;
  }
  return true;
};

console.log(canFormSequence(arr1, arr2));

ข้อผิดพลาดในตรรกะ

โค้ดตรวจสอบ commonDifference แบบคงที่ แต่สำหรับ consecutive sequence ความต่างต้องเป็น -1 เสมอ (เพราะเรียงน้อยไปมาก)

โค้ดที่ถูกต้อง

const canFormSequence = (arr1, arr2) => {
  const combined = [...arr1, ...arr2].sort((a, b) => a - b);
  for (let i = 1; i < combined.length; i++) {
    if (combined[i] - combined[i - 1] !== 1) return false;
  }
  return true;
};

ผลลัพธ์

true