Skip to content

Triangle

Intro

An equilateral triangle has all three sides the same length.

An isosceles triangle has at least two sides the same length. (It is sometimes specified as having exactly two sides the same length, but for the purposes of this exercise we'll say at least two.)

A scalene triangle has all sides of different lengths.

Note

For a shape to be a triangle at all, all sides have to be of length > 0, and the sum of the lengths of any two sides must be greater than or equal to the length of the third side. See Triangle Inequality.

Task

Determine if a triangle is equilateral, isosceles, or scalene.

The Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include <stdexcept>

namespace triangle {
flavor kind(double a, double b, double c) {
    if (a <= 0 || b <= 0 || c <= 0 || a + b < c || a + c < b || b + c < a)
        throw std::domain_error("error");
    std::map<double, double> sisi{};
    sisi[a]++;
    sisi[b]++;
    sisi[c]++;
    if (sisi.at(a) == 3)
        return flavor::equilateral;
    if ((sisi.at(a) == 2 && (sisi.at(b) == 1 || sisi.at(c) == 1))
            || (sisi.at(a)==1 && sisi.at(b)==2))
        return flavor::isosceles;
    return flavor::scalene;
}
} // namespace triangle
1
2
3
4
5
6
7
8
9
#if !defined(TRIANGLE_H)
#define TRIANGLE_H

namespace triangle {
enum class flavor {equilateral,isosceles,scalene};
flavor kind(double,double,double);
}  // namespace triangle

#endif // TRIANGLE_H

Last update: February 13, 2021

Comments