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

ตรวจสอบว่าหมุนหน้ากระดาษได้หรือไม่จากจุด 3 จุดใน C++

โจทย์

ได้รับพิกัด 3 จุด x, y, z บนหน้ากระดาษ ทางเราต้อง ตรวจสอบว่าสามารถหมุนหน้ากระดาษได้หรือไม่ ทำให้ตำแหน่งใหม่ของ x = ตำแหน่งเก่าของ y, y = z

ตัวอย่าง

Input: x=(0,1), y=(1,0), z=(0,-1)

Output: Yes

อธิบาย: หมุน 90 องศาได้

แนวทางแก้ปัญหา

เงื่อนไขที่สามารถหมุนได้:

  1. ระยะห่างระหว่าง x และ y เท่ากับระยะห่างระหว่าง y และ z
  2. จุดทั้งสาม ไม่ควรอยู่บนเส้นตรงเดียวกัน (Collinear)

โปรแกรมตัวอย่าง

#include <bits/stdc++.h>
using namespace std;

int possibleOrNot(int coordinates[3][2]) {
    long long dis1 = pow(coordinates[1][0] - coordinates[0][0], 2) + pow(coordinates[1][1] - coordinates[0][1], 2);
    long long dis2 = pow(coordinates[2][0] - coordinates[1][0], 2) + pow(coordinates[2][1] - coordinates[1][1], 2);
    if (dis1 != dis2) return 0;
    else if (coordinates[1][0] == (coordinates[0][0] + coordinates[2][0]) / 2.0 &&
             coordinates[1][1] == (coordinates[0][1] + coordinates[2][1]) / 2.0)
        return 0;
    else return 1;
}

int main() {
    int coordinates[3][2] = {{0, 1}, {1, 0}, {0, -1}};
    if (possibleOrNot(coordinates)) cout << "The rotation of page is possible";
    else cout << "The rotation of page is not possible";
    return 0;
}

ผลลัพธ์

The rotation of page is possible