Sherlock and Planes

  • + 0 comments

    A problem like this leads to an interesting variety of solutions.

    The most obvious approach would be to substitute 3 of these points into the general equation of a plane (ax + by + cz + d = 0) and see if the 4th point satisfies this equation.

    This would require a fair bit of matrix work so instead, I chose 3 different pairs of points and made vectors out of them then calculated the cross product out of two different pairs of these vectors. If all points are in the same plane then the two cross products should be scalar multiples of each other.

    #include <stdio.h>
    #include <stdbool.h>
    
    void crossProduct(int *v1, int *v2, int *res) {
        res[0] = v1[1] * v2[2] - v1[2] * v2[1];
        res[1] = v1[2] * v2[0] - v1[0] * v2[2];
        res[2] = v1[0] * v2[1] - v1[1] * v2[0];
    }
    
    bool inPlane (int points[4][3]) {
        int vec[3][3];
        for (int i = 0; i < 3; ++i) {
            for (int j = 0; j < 3; ++j) {
                vec[i][j] = points[i][j] - points[3][j];
            }
        }
        int n1[3], n2[3];
        crossProduct(vec[0], vec[1], n1);
        crossProduct(vec[1], vec[2], n2);
        if (n1[0] * n2[1] != n1[1] * n2[0]) return false;
        if (n1[1] * n2[2] != n1[2] * n2[1]) return false;
        return true;
    }
    
    int main() {
        int t, points[4][3];
        scanf("%d", &t);
        while (t--) {
            for (int i = 0; i < 4; ++i) {
                for (int j = 0; j < 3; ++j) scanf("%d", &points[i][j]);
            }
            printf("%s\n", inPlane(points) ? "YES" : "NO");
        }
        return 0;
    }