Small Triangles, Large Triangles || Hacker Rank

 Question 20 || Hacker Rank

Small Triangles, Large Triangles || Hacker Rank

Small Triangles, Large Triangles


You are given n triangles, explicitly, their sides ai, bi and ci. Print them in a similar style however arranged by their region from the littlest one to the biggest one. It is ensured that every one of the areas are unique.

 

The most effective way to compute a region of a triangle with sides a, b and c is Heron's formula:

 

Small Triangles, Large Triangles


 Input Configuration

The main line of each test record contains a solitary whole number n. lines follow with three space-isolated whole numbers ai, bi and ci

 

Imperatives

 

Small Triangles, Large Triangles

Yield Configuration

Print precisely lines. On each line print space-isolated numbers and of the relating triangle.

 

Test Info 0

3

7   24   25

5   12   13

3   4   5

Test Result 0

3   4   5

5   12   13

7   24   25

 

Clarification 0

The square of the main triangle is 84. The square of the second subsequent triangle is 30. The square of the third triangle is 6. So, the arranged request is the converse i.e., reverse one.



Source Code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

struct triangle
{
    int a;
    int b;
    int c;
};

typedef struct triangle triangle;
double area(triangle tr) 
{
    double p = (tr.a + tr.b + tr.c) / 2.0;
    return sqrt(p * (p - tr.a) * (p - tr.b) * (p - tr.c));
}

int compare(const void *a, const void *b) 
{
    triangle *t1 = (triangle*) a;
    triangle *t2 = (triangle*) b;
    double area1 = area(*t1);
    double area2 = area(*t2);
    if (area1 > area2) 
    {
        return 1;
    } else if (area1 < area2) 
    {
        return -1;
    } else 
    {
        return 0;
    }
}

void sort_by_area(triangle* tr, int n) 
{
    qsort(tr, n, sizeof(triangle), compare);
}

int main()
{
    int n;
    scanf("%d", &n);
    triangle *tr = malloc(n * sizeof(triangle));
    for (int i = 0; i < n; i++) {
        scanf("%d%d%d", &tr[i].a, &tr[i].b, &tr[i].c);
    }
    sort_by_area(tr, n);
    for (int i = 0; i < n; i++) {
        printf("%d %d %d\n", tr[i].a, tr[i].b, tr[i].c);
    }
    return 0;
}




Output:

Small Triangles, Large Triangles



Post a Comment

0 Comments