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

ตรวจสอบจุดสามจุดว่าอยู่บนเส้นตรงเดียวกัน (Collinear) - JavaScript

จุด一直線 (Collinear Points) คือจุดสามจุดขึ้นไปที่อยู่บนเส้นตรงเดียวกัน เงื่อนไขคือความชัน (slope) ของทุกคู่จุดต้องเท่ากัน

สูตรความชัน

กำหนดจุด A(x₁, y₁) และ B(x₂, y₂)

Slope = (y₂ - y₁) / (x₂ - x₁)

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

const a = {x: 2, y: 4};
const b = {x: 4, y: 6};
const c = {x: 6, y: 8};

const slope = (coor1, coor2) => (coor2.y - coor1.y) / (coor2.x - coor1.x);

const areCollinear = (a, b, c) => {
  return slope(a, b) === slope(b, c) && slope(b, c) === slope(c, a);
};

console.log(areCollinear(a, b, c));

ผลลัพธ์

true

ข้อควรระวัง

  • การหารด้วยศูนย์ (vertical line) จะได้ Infinity ต้องจัดการแยก
  • การเปรียบเทียบ floating point อาจมีปัญหาความแม่นยำ ควรใช้ epsilon comparison
// ปรับปรุงสำหรับ vertical line และ precision
const areCollinearRobust = (a, b, c) => {
  const area = a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y);
  return Math.abs(area) < 1e-10; // ใช้พื้นที่สามเหลี่ยม = 0
};