Nearly Similar Rectangles
Recently, while researching about similar rectangles, you found the term "Nearly Similar Rectangle." Two rectangles with sides (a, b) and (c,d) are nearly similar only if a/c = b/d. The order of sides matter in this definition, so rectangles [4, 2] and [6,3] are nearly similar, but rectangles [2, 4] and [6,3] are not. Given an array of rectangles with the lengths of their sides, calculate the number of pairs of nearly similar rectangles in the array.
For example, let's say there are n = 4 rectangles, and sides = [[5, 10), [10, 10), (3, 6), 19, 9]]. In this case, the first and third rectangles, with sides [5, 10] and [3,6], are nearly similar because 5/3 = 10/6. Also, the second and fourth rectangles, with sides [10, 10] and [9, 9], are nearly similar because 10/9 = 10/9. This means there are 2 pairs of nearly similar rectangles in the array. Therefore, the answer is 2.
Function Description
Complete the function nearly SimilarRectangles in the editor below.
nearlySimilarRectangles has the following parameter:
int sides[n][2]: a 2-dimensional integer array where the throw denotes the sides of the ith rectangle
Returns:
Int: the number of nearly similar rectangles in the array
Constraints
• 1 ≤ n ≤ 105
• 1 ≤ [i][0], sides[i][1] ≤ 1015
Input Format For Custom Testing
The first line contains an integer, n, denoting the number of rows in sides.
The next line contains an integer, 2, denoting the number of columns in sides.
Each line i of the n subsequent lines (where 0 ≤i<n) contains 2 space-separated integers, sides[i][0] and sides[i][1], denoting the lengths of the ith rectangle's sides
Solution in Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #!/bin/python3 import math import os import random import re import sys from collections import defaultdict # # Complete the 'nearlySimilarRectangles' function below. # # The function is expected to return a LONG_INTEGER. # The function accepts 2D_LONG_INTEGER_ARRAY sides as parameter. # def nearlySimilarRectangles(sides): gcd = lambda a, b: gcd(b, a % b) if b > 0 else a d = defaultdict(int) for w, h in sides: z = gcd(w, h) d[(w // z, h // z)] += 1 return sum((x * (x - 1)) // 2 for x in d.values()) if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') sides_rows = int(input().strip()) sides_columns = int(input().strip()) sides = [] for _ in range(sides_rows): sides.append(list(map(int, input().rstrip().split()))) result = nearlySimilarRectangles(sides) fptr.write(str(result) + '\n') fptr.close() |