mirror of
https://github.com/correl/euler.git
synced 2024-12-25 03:00:08 +00:00
Haskell 009 documented and using a data structure
This commit is contained in:
parent
c0ab42edf9
commit
71824cf748
1 changed files with 17 additions and 6 deletions
|
@ -10,18 +10,29 @@ Find the product abc.
|
|||
|
||||
import Text.Printf
|
||||
|
||||
-- |A triangle consisting of three integral sides
|
||||
data Triangle = Triangle Int Int Int
|
||||
|
||||
-- |Return the product of the sides of the first triangle having the sum of the sides 'sum'
|
||||
triplet :: Int -> Int
|
||||
triplet sum = do
|
||||
let cs = reverse (takeWhile (<= sum - 3) [3,5..])
|
||||
let tri = head (concat (map (\x -> diffs sum x) cs))
|
||||
let (a, b, c) = tri
|
||||
let tri = head (concat (map (\x -> right_triangles sum x) cs))
|
||||
let (Triangle a b c) = tri
|
||||
a * b * c
|
||||
diffs sum c = do
|
||||
|
||||
-- |Find all right triangles having sum of sides 'sum' and side c length of 'c'
|
||||
right_triangles :: Int -> Int -> [Triangle]
|
||||
right_triangles sum c = do
|
||||
let diff = sum - c
|
||||
let range = [1..(floor ((fromIntegral diff) / 2)) + 1]
|
||||
let triangles = filter is_triangle (map (\x -> (x, diff - x, c)) range)
|
||||
let triangles = filter is_right_triangle (map (\x -> Triangle x (diff - x) c) range)
|
||||
triangles
|
||||
is_triangle (a, b, c) =
|
||||
|
||||
-- |Return whether the provided triangle is a right triangle using the pythagorean theorem
|
||||
is_right_triangle :: Triangle -> Bool
|
||||
is_right_triangle (Triangle a b c) =
|
||||
a^2 + b^2 == c^2
|
||||
|
||||
main = do
|
||||
printf "Pythagorean triplet product having a + b + c = 1000: %d\n" (triplet 1000 :: Integer)
|
||||
printf "Pythagorean triplet product having a + b + c = 1000: %d\n" (triplet 1000 :: Int)
|
||||
|
|
Loading…
Reference in a new issue