You are viewing a single comment's thread. Return to all comments →
WHEN 2 * GREATEST(A, B, C) >= (A + B + C) THEN "Not A Triangle"
WHEN A = B AND A = C THEN "Equilateral"
WHEN A = B OR A = C OR B = C THEN "Isosceles"
I had very similar code but I put the 'Iscoceles' case statment before the 'Not a Triangle' one and it caused an error. The order in which you check the statments can really reduce the logic in your code :)
SELECT CASE WHEN C >= A + B THEN 'Not A Triangle' WHEN A = B AND B = C THEN 'Equilateral' WHEN A = B OR A = C OR B = C THEN 'Isosceles' ELSE 'Scalene' END AS 'Triangles' FROM TRIANGLES;
Exactly! I have been saying that in few comments!
You don't need to have multiple CASE statements next to each other or nested CASEs. If you check the conditions in the right order, only one CASE statement with multiple WHENs will do the job:
SELECT CASE WHEN A + B <= C OR A + C <= B OR B + C <= A THEN 'Not A Triangle'
WHEN A = B AND B = C THEN 'Equilateral'
WHEN A = B OR A = C OR B = C THEN 'Isosceles'
I think this is the cleanest and shortest answer...
When the Isosceles and Equilateral case statements order are reversed, that is the Equi is checked after Isos then the test case fails. Is it a necessaity to do this in this ordeR?
Hello, can you please explaing this...
WHEN 2 * GREATEST(A, B, C) >= (A + B + C)
Thank you in advance!
The general rule/condition for a valid triangle is that the longest side should be less than the sum of the two other sides:
longestSide < sumOfOtherSides (1)
longestSide < sumOfOtherSides
For example, if you have A, B, and C, where B is the longest side, then the condition B < (A+C) is true for a valid triangle, and false otherwise.
B < (A+C)
Now, the sum of all the sides of the triangle is (A+B+C). Given B is the longest side, if you want to get the sum of other sides, you have to remove B from the sum of all sides, thus (A+C) = (A+B+C) - (B) or in other words:
(A+C) = (A+B+C) - (B)
sumOfOtherSides = sumOfAllSides - longestSide (2)
sumOfOtherSides = sumOfAllSides - longestSide
With this in mind, the first inequation (1) can now be written as :
longestSide < sumOfAllSides - longestSide
which is equivalent to
longestSide + longestSide < sumOfAllSides
2 * longestSide < sumOfAllSides (3)
2 * longestSide < sumOfAllSides
So, a triangle is valid if and only if inequation (3) is true. If (3) is false, then we have 2 * longestSide >= sumOfAllSides. In MySQL and Oracle SQL, the GREATEST() function returns the greatest value of the guiven arguments. Hence, you have longestSide = GREATEST(A, B, C).
2 * longestSide >= sumOfAllSides
longestSide = GREATEST(A, B, C)
Everything above put together, the final formula to check if a triangle is NOT valid is :
2 * GREATEST(A, B, C) >= (A + B + C)
Hope my explanation was clear and detailed!
Thank you for sharing this information.
This fails in Oracle due to double quote: ""
I'd advise to use '' as standard for strings an dates.
sigh took me a while to realize I needed single quotes