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

การตรวจสอบเส้นตรงใน JavaScript


ภาพรวม

เราต้องเขียนฟังก์ชันที่รับอาร์เรย์ของอาร์เรย์ แต่ละอาร์เรย์ย่อยมีสองค่า แทนพิกัด x และ y ฟังก์ชันควรตรวจสอบว่าพิกัดเหล่านี้อยู่บนเส้นตรงเดียวกันหรือไม่

ตัวอย่าง

[[4, 5], [5, 6]] should return true.

อาร์เรย์รับประกันว่ามีอย่างน้อยสองอาร์เรย์ย่อย

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

const coordinates = [
  [4, 5],
  [5, 6]
];

const checkStraightLine = (coordinates = []) => {
  if(coordinates.length === 0) return false;
  let x1 = coordinates[0][0];
  let y1 = coordinates[0][1];
  let slope1 = null;
  
  for(let i = 1; i < coordinates.length; i++) {
    let x2 = coordinates[i][0];
    let y2 = coordinates[i][1];
    
    if(x2 - x1 === 0) {
      return false;
    }
    
    if(slope1 === null) {
      slope1 = (y2 - y1) / (x2 - x1);
      continue;
    }
    
    let slope2 = (y2 - y1) / (x2 - x1);
    if(slope2 != slope1) {
      return false;
    }
  }
  return true;
};

console.log(checkStraightLine(coordinates));

คำอธิบาย

เราคำนวณความชันของแต่ละจุดกับจุดแรก หากความชันเท่ากันทุกจุด แสดงว่าอยู่บนเส้นตรงเดียวกัน

ผลลัพธ์ในคอนโซล

true