Skip to content

Commit 7c96ac7

Browse files
authored
Create 2001-number-of-pairs-of-interchangeable-rectangles.c
Create the C solution as the same solution in the YouTube video "https://www.youtube.com/watch?v=lEQ8ZlLOuyQ"
1 parent 9154cf7 commit 7c96ac7

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
typedef struct hash_entry {
2+
double* ratio; /* we'll use this field as the key */
3+
long long count;
4+
UT_hash_handle hh; /* makes this structure hashable */
5+
} hash_entry;
6+
7+
long long interchangeableRectangles(int** rectangles, int rectanglesSize, int* rectanglesColSize){
8+
hash_entry* ratioCountMap = NULL;
9+
long long res = 0;
10+
11+
for(size_t i = 0; i < rectanglesSize; i++)
12+
{
13+
// Calculate the ratio (W / H)
14+
double* ratio = (double*)malloc(sizeof(double));
15+
*ratio = (double)rectangles[i][0] / rectangles[i][1];
16+
17+
hash_entry* retrievedMapEntry;
18+
HASH_FIND_PTR(ratioCountMap, ratio, retrievedMapEntry);
19+
20+
// If the ratio already exists in the map then increment its count
21+
if(retrievedMapEntry)
22+
{
23+
// Free the allocated memory for the ratio
24+
free(ratio);
25+
retrievedMapEntry->count += 1;
26+
}
27+
else
28+
{
29+
// If the ratio doesn't exist in the map then create a new map entry for it and add it to the map
30+
hash_entry* mapEntryToAdd = (hash_entry*)malloc(sizeof(hash_entry));
31+
mapEntryToAdd->ratio = ratio;
32+
mapEntryToAdd->count = 1;
33+
HASH_ADD_KEYPTR(hh, ratioCountMap, mapEntryToAdd->ratio, sizeof(double), mapEntryToAdd);
34+
}
35+
}
36+
37+
for (hash_entry* retrievedMapEntry = ratioCountMap; retrievedMapEntry != NULL; retrievedMapEntry = retrievedMapEntry->hh.next)
38+
{
39+
res += (retrievedMapEntry->count * (retrievedMapEntry->count - 1)) / 2;
40+
}
41+
42+
return res;
43+
}

0 commit comments

Comments
 (0)