HackerRank C- Small Triangles, Large Triangles




You are given n triangles, specifically, their sides a1, b1 and c1. 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 volume of the triangle with sides a, b and c is Heron's formula:



  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. struct triangle
  5. {
  6. int a;
  7. int b;
  8. int c;
  9. };
  10. typedef struct triangle triangle;
  11. void sort_by_area(triangle *tr, int n) {
  12. // Sort an array a of the length n
  13. int *p=malloc(n*sizeof(int));
  14. //create array of size n to store "volumes"
  15. for(int i=0;i<n;i++)
  16. {
  17. float a=(tr[i].a+tr[i].b+tr[i].c)/2.0;
  18. //use 2.0 compulsary int/int gives int, int/float gives float
  19. p[i]=(a*(a-tr[i].a)*(a-tr[i].b)*(a-tr[i].c));
  20. //formula without sqrt as areas are different guarenteed
  21. //because sqrt dosent work well with float values
  22. }
  23. //bubble sort
  24. for(int i=0;i<n;i++)
  25. {
  26. for(int j=0;j<n-i-1;j++)
  27. {
  28. if(p[j]>p[j+1])
  29. {
  30. int temp=p[j];
  31. p[j]=p[j+1];
  32. p[j+1]=temp;
  33. //swapping array of areas in ascending
  34. //and simuntaneously the structure contents
  35. temp=tr[j].a;
  36. tr[j].a=tr[j+1].a;
  37. tr[j+1].a=temp;
  38. temp=tr[j].b;
  39. tr[j].b=tr[j+1].b;
  40. tr[j+1].b=temp;
  41. temp=tr[j].c;
  42. tr[j].c=tr[j+1].c;
  43. tr[j+1].c=temp;
  44. }
  45. }
  46. }
  47. }
  48. int main()
  49. {
  50. int n;
  51. scanf("%d", &n);
  52. triangle *tr = malloc(n * sizeof(triangle));
  53. for (int i = 0; i < n; i++) {
  54. scanf("%d%d%d", &tr[i].a, &tr[i].b, &tr[i].c);
  55. }
  56. sort_by_area(tr, n);
  57. for (int i = 0; i < n; i++) {
  58. printf("%d %d %d\n", tr[i].a, tr[i].b, tr[i].c);
  59. }
  60. return 0;
  61. }
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]


donate a cup of tea :)


Join Our Facebook Group

Share this solution






codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube