Nearly Similar Rectangles problem solved

This Python program is designed to solve a problem related to geometry and number theory. It takes as input a list of rectangles, represented by their sides, and calculates how many pairs of rectangles are 'nearly similar'. Two rectangles are considered 'nearly similar' if the ratios of their sides are the same.

Secure your next interview 🎯

CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷

Here is the Nearly Similar Rectangles problem solved from HackerRank using CodeRankGPT:

The solution works by first defining a function to calculate the greatest common divisor (gcd) of two numbers. This is used to simplify the ratios of the sides of the rectangles. The program then iterates over the list of rectangles, calculating the simplified ratio of each rectangle's sides and storing the count of each ratio in a dictionary. Finally, it calculates the number of pairs of rectangles that have the same ratio, which is equivalent to the number of 'nearly similar' rectangles. The key algorithm used here is the Euclidean algorithm for calculating the gcd, and the approach is based on counting and combinatorics.


import math
import os
import random
import re
import sys

from collections import defaultdict

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) + '
')

    fptr.close()

If you have a HackerRank Certification test or a coding interview coming up, you can use CodeRankGPT to your advantage. It will assist you during your test and help ensure you get the certification or the job.

AI is here now, and other candidates might be using it to get ahead and win the job. 🧐

Built on Unicorn Platform