Algorithm


Problem Name: Small Triangles, Large Triangles

Problem Link: https://www.hackerrank.com/challenges/small-triangles-large-triangles/problem?isFullScreen=true

In this HackerRank Functions in C programming problem solution,

In this Small Triangles, Large Triangles in c programming problem solution You are given n triangles, specifically, their sides ai, bi, and ci. Print them in the same style but sorted by their areas from the smallest one to the largest one. It is guaranteed that all the areas are different.

The best way to calculate a area of a triangle with sides a, b and c is Heron's formula:

S = SQRT P*(p-a)*(p-b)*(p-c) where

p = (a+b+c)/2

Input Format

The first line of each test file contains a single integer n. n ines follow with three space-separated integers,ai, bi, and ci.

Constraints

  • 1 <= n <= 100
  • 1 <= ai,bi,ci <= 70
  • ai + bi > ci,ai +ci > bi and ci of the corresponding triangle.

    Sample Input 0

    3
    7 24 25
    5 12 13
    3 4 5
    

    Sample Output 0

    3 4 5
    5 12 13
    7 24 25
    

 

Code Examples

#1 Code Example with C Programming

Code - C Programming


#include <math.h>

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

typedef struct triangle triangle;
void sort_by_area(triangle* tr, int n)
{
    double area[n], s;
    int i;
    for(i = 0; i  <  n; i++){
        s = (tr[i].a + tr[i].b + tr[i].c ) / 2.0;

        area[i] = sqrt(s * (s - tr[i].a) * (s - tr[i].b) * (s - tr[i].c));
    }

    int j, k;
    double tempArea;
    struct triangle temp;
    for(k = 0; k  <  n; k++){
        for(j = 0; j  <  n - k - 1; j++){
            if(area[j] > area[j + 1]){
                temp = tr[j];
                tr[j] = tr[j + 1];
                tr[j + 1] = temp;

                tempArea = area[j];
                area[j] = area[j + 1];
                area[j + 1] = tempArea;
            }
        }
    }
}

int main(void)
{
	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;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
3 7 24 25 5 12 13 3 4 5

Output

x
+
cmd
3 4 5 5 12 13 7 24 25
Advertisements

Demonstration


Previous
[Solved] Playing With Characters in C solution in Hackerrank - Hacerrank solution C
Next
[Solved] Querying the Document in C solution in Hackerrank - Hacerrank solution C