nikunjsoni

593

Jul 28th, 2021
482
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Solution {
  2. public:
  3.     // helper function to calculate distance between two points
  4.     int dist(vector<int>& p1, vector<int>& p2) {
  5.         return (p2[0] - p1[0]) * (p2[0] - p1[0]) + (p2[1] - p1[1]) * (p2[1] - p1[1]);
  6.     }
  7.    
  8.     bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
  9.         // keep points in an array to be able to get them by index
  10.         vector<vector<int>> points = {p1, p2, p3, p4};
  11.         set<int> lengths;
  12.        
  13.         for (int i=0; i<4; i++) {
  14.             for (int j=i+1; j<4; j++) {
  15.                 int curr = dist(points[i], points[j]);
  16.                 if (curr != 0)
  17.                     lengths.insert(curr);
  18.                
  19.                 // if distance is zero - we got a duplicated point
  20.                 else
  21.                     return false;
  22.             }
  23.         }
  24.         // We are supposed to end with only two different lengths: the sides and the diagonals
  25.         return lengths.size() == 2;
  26.     }
  27. };
RAW Paste Data