Skip to content

Instantly share code, notes, and snippets.

@Aldizh
Created January 25, 2021 16:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aldizh/5e8bf70a708239df996e006f390ecc74 to your computer and use it in GitHub Desktop.
Save Aldizh/5e8bf70a708239df996e006f390ecc74 to your computer and use it in GitHub Desktop.
Pairs of similar rectangles
/*
Given a 2D array A[][2] of size N (1 ≤ N ≤ 103), where A[i][0] and A[i][1] denotes the length and breadth of rectangle i respectively.
Two rectangle i and j where (i < j) are similar if the ratio of their length and breadth is equal
A[i][0] / A[i][1] = A[j][0] / A[j][1]
Input : A[][2] = {{4, 8}, {15, 30}, {3, 6}, {10, 20}}
Output: 6
Explanation: Pairs of similar rectangles are (0, 1), {0, 2), (0, 3), (1, 2), (1, 3), (2, 3). For every rectangle, ratio of length : breadth is 1 : 2
Input : A[][2] = {{2, 3}, {4, 5}, {7, 8}}
Output: 0
Explanation: No pair of similar rectangles exists.
Approach: Follow the steps to solve the problem
Traverse the array.
For every pair such that (i < j), check whether the rectangles are similar or not by checking if the condition A[i][0] / A[i][1] = A[j][0] / A[j][1] is satisfied or not.
If found to be true, increment the count.
Finally, print the count obtained.
*/
function getMatchingPairs(arr){
let count = 0;
for (var i = 0; i<arr.length; i++){
for (var j = i+1; j<arr.length; j++){
// let prod1 = arr[i][0] * arr[j][1]
// let prod2 = arr[i][1] * arr[j][0]
// if (prod1 === prod2) count += 1
let div1 = arr[i][0] / arr[j][0]
let div2 = arr[i][1] / arr[j][1]
if (div1.toFixed(2) === div2.toFixed(2)) count += 1
}
}
return count
}
// test cases
// [4, 8], [15, 30], [3, 6], [10, 20]] => 6
// [[2, 3], [4, 5], [7, 8]] => 0
// [[2, 3], [4, 6], [7, 8]] => 1
var rectsArr = [[4, 8], [15, 30], [3, 6], [10, 20]]
getMatchingPairs(rectsArr)
@andrewinsoul
Copy link

Saw this kind of problem and the solution of looping inside of a loop was what I could think of but Hackerank complained of time complexity. Is there another way this can be achieved without looping inside of a for loop

@Emma1963
Copy link

You can try to use Dictionary

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment