Matrix chain multiplication: Difference between revisions
Content added Content deleted
(→{{header|Haskell}}: Suggested edit (OP may prefer to revert): applied hlint hindent, specified imports) |
|||
Line 374: | Line 374: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
<lang Haskell> |
<lang Haskell>import Data.Maybe (fromJust) |
||
import Data.List |
import Data.List (elemIndex) |
||
import Data.Char |
import Data.Char (chr, ord) |
||
import Data.Maybe |
|||
mats |
mats :: [[Int]] |
||
mats = |
|||
⚫ | |||
[ [5, 6, 3, 1] |
|||
⚫ | |||
, [1000, 1, 500, 12, 1, 700, 2500, 3, 2, 5, 14, 10] |
|||
] |
|||
cost |
cost :: [Int] -> Int -> Int -> (Int, Int) |
||
cost a i j |
|||
⚫ | |||
| i < j = |
|||
⚫ | |||
let m = |
|||
⚫ | |||
(a !! i) * (a !! (j + 1)) * (a !! (k + 1)) |
|||
| k <- [i .. j - 1] ] |
|||
in let mm = minimum m |
|||
⚫ | |||
| otherwise = (0, -1) |
|||
optimalOrder |
optimalOrder :: [Int] -> Int -> Int -> String |
||
optimalOrder a i j |
|||
⚫ | |||
| i < j = |
|||
let c = cost a i j |
|||
⚫ | |||
| otherwise = [chr ((+ i) $ ord 'a')] |
|||
printBlock |
printBlock :: [Int] -> IO () |
||
printBlock v = |
|||
putStrLn ("for " ++ (show $ v) ++ " we have " ++ (show $ (fst c)) ++ " possibilities, z.B " ++ |
|||
let c = cost v 0 (length v - 2) |
|||
in putStrLn |
|||
("for " ++ |
|||
show v ++ |
|||
" we have " ++ |
|||
show (fst c) ++ |
|||
" possibilities, z.B " ++ optimalOrder v 0 (length v - 2)) |
|||
main |
main :: IO () |
||
main = mapM_ printBlock mats</lang> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
⚫ | |||
<pre> |
|||
⚫ | |||
for [1,5,25,30,100,70,2,1,100,250,1,1000,2] we have 38120 possibilities, z.B ((((((((ab)c)d)e)f)g)(h(ij)))(kl)) |
for [1,5,25,30,100,70,2,1,100,250,1,1000,2] we have 38120 possibilities, z.B ((((((((ab)c)d)e)f)g)(h(ij)))(kl)) |
||
for [1000,1,500,12,1,700,2500,3,2,5,14,10] we have 1773740 possibilities, z.B (a((((((bc)d)(((ef)g)h))i)j)k) |
for [1000,1,500,12,1,700,2500,3,2,5,14,10] we have 1773740 possibilities, z.B (a((((((bc)d)(((ef)g)h))i)j)k)</pre> |
||
</pre> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |