سؤال

Problem statement:

Find the right triangle that has integers for all sides and all sides equal to or smaller than 10 has a perimeter of 24.

Which solution of following two is correctly interpreting the problem and gives the right answer?

If the First Solution is not correct then how to avoid such programming error in similar scenario?

First Solution:

ghci> let rightTriangles = [(a, b, c) | a <- [1..10], b <- [1..10], c <- [1..10], a^2 + b^2 == c^2, a+b+c == 24]
ghci> rightTriangles
[(6,8,10),(8,6,10)]

Second Solution:

ghci> let rightTriangles' = [ (a,b,c) | c <- [1..10] , b <- [1..c] , a <- [1..b] , a^2 + b^2 == c^2, a+b+c == 24]
ghci> rightTriangles'
[(6,8,10)]
هل كانت مفيدة؟

المحلول

As it stands I think the problem is slightly under defined.

The first four words "Find the right triangle" (emphasis mine) suggests a unique answer, which is almost certainly meant to be (6,8,10). However the rest of the problem is met by all triangles that are congruent to (6,8,10), of which (8,6,10) is certainly one so it is not wrong per se, but probably not what you are meant to get.

Another way of looking at this is that the problem defines an equivalence class of which (6,8,10) is the canonical representation, however the problem does not explicitly ask for the canonical representation (though we can infer it is probably the expected answer and therefore should use your second solution)

نصائح أخرى

You have to filter out different permutations. By restriction a <= b and b <= c, you can accomplish this. You did this in the second answer by restriction the input domain of b and c. b <- [1..c] implies b <= c.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top