Triangle

Triangle

Medium

Instructions

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

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.

In equations:

Let a, b, and c be sides of the triangle. Then all three of the following expressions must be true:

a + b ≥ c
b + c ≥ a
a + c ≥ b

See Triangle Inequality

Implementation of this can take many forms. Here are some topics that may help you, depending on the approach you take.

Or maybe you will come up with an approach that uses none of those!

Non-integer lengths

The base exercise tests identification of triangles whose sides are all integers. However, some triangles cannot be represented by pure integers. A simple example is a right triangle (an isosceles triangle whose equal sides are separated by 90 degrees) whose equal sides both have length of 1. Its hypotenuse is the square root of 2, which is an irrational number: no simple multiplication can represent this number as an integer.

It would be tedious to rewrite the analysis functions to handle both integer and floating-point cases, and particularly tedious to do so for all potential integer and floating point types: given signed and unsigned variants of bitwidths 8, 16, 32, 64, and 128, that would be 10 reimplementations of fundamentally the same code even before considering floats!

There's a better way: generics. By rewriting your Triangle as a Triangle<T>, you can write your code once, and hand off the work of generating all those specializations to the compiler. Note that in order to use mathematical operations, you'll need to constrain your generic type to types which support those operations using traits.

There are some bonus tests you can run which test your implementation on floating-point numbers. To enable them, run your tests with the generic feature flag, like this:

cargo test --features generic
Edit via GitHub The link opens in a new window or tab
Rust Exercism

Ready to start Triangle?

Sign up to Exercism to learn and master Rust with 96 exercises, and real human mentoring, all for free.