Simple JavaScript solution using distance


  • 0
    var validSquare = function(p1, p2, p3, p4) {
        if (new Set([p1.join(','), p2.join(','), p3.join(','), p4.join(',')]).size !== 4) return false;
        const points = [p1, p2, p3, p4];
        const combos = [[0,1,2], [0,1,3], [0,2,3], [1,2,3]];
        const dists = new Set();
        for (let c of combos) {
            dists.add(dist(points[c[0]], points[c[1]]));
            dists.add(dist(points[c[1]], points[c[2]]));
            dists.add(dist(points[c[0]], points[c[2]]));
        }
        return dists.size === 2;
    };
    
    function dist(a, b) {
        return Math.pow(a[0] - b[0], 2) + Math.pow(a[1] - b[1], 2);
    }
    

    Among all possible distances, there should be only two: the side distance and the hypotenuse distance.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.