jag*_*ofy 1 optimization haskell
--Returns last N elements in list
lastN :: Int -> [a] -> [a]
lastN n xs = let m = length xs in drop (m-n) xs
--create contiguous array starting from index b within list a
produceContiguous :: [a] -> Int -> [[a]]
produceContiguous [] _ = [[]]
produceContiguous arr ix = scanl (\acc x -> acc ++ [x]) [arr !! ix] inset
where inset = lastN (length arr - (ix + 1)) arr
--Find maximum sum of all possible contiguous sub arrays, modulo [n]
--d is dummy data
let d = [1,2,3,10,6,3,1,47,10]
let maxResult = maximum $ map (\s -> maximum s) $ map (\c -> map (\ac -> (sum ac )`mod` (last n)) c ) $ map (\n -> produceContiguous d n ) [0..(length d) -1]
Run Code Online (Sandbox Code Playgroud)
我是一个Haskell的新手 - 就在几天之内......如果我做的事情显然是错的,那就是哎呀
您可以通过观察map sum (produceContiguous d n)(运行时间为Ω(m ^ 2),长度为drop n d- 可能是O(m ^ 3)时间,因为您acc在每次迭代时附加到结束时)可以大大改善运行时间折叠为scanl (+) 0 (drop n d)(具有运行时O(m)).我还会做出很多其他的风格变化,但这是我能想到的主要算法.
清理所有风格的东西,我可能会写:
import Control.Monad
import Data.List
addMod n x y = (x+y) `mod` n
maxResult n = maximum . (scanl (addMod n) 0 <=< tails)
Run Code Online (Sandbox Code Playgroud)
在ghci:
*Main> jaggedGoofyMax 100 [1..1000]
99
(12.85 secs, 24,038,973,096 bytes)
*Main> dmwitMax 100 [1..1000]
99
(0.42 secs, 291,977,440 bytes)
Run Code Online (Sandbox Code Playgroud)
这里没有展示的版本jaggedGoofyMax已经只有我在我的应用第一款,其中有稍微好一点的运行时间/内存使用状态所提到的优化dmwitMax时,在ghci中(但基本上等同于运行dmwitMax时都被编译-O2).因此,您可以看到,即使是适度的输入大小,这种优化也会产生很大的不同.
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |