作为练习练习我决定编写一个滑动拼图解算器(如8拼图或15拼图)。现在,解决方案就在那里,它正在运行,但我现在面临的问题是运行时。我想请求一些优化解决方案的帮助(如果可能的话)。我很想知道可以采取哪些步骤来提高他们的Haskell程序的性能。
我的实施可在此处找到:https://gist.github.com/anonymous/166d8a3323a3f96eab04
示例输入文件:
4
5 4 3 8
9 2 6 1
0 13 14 7
15 11 10 12
如果在分析器下运行它,您将看到我们生成的数据量大约为9Gb。 “有问题”的功能是manhattan
和boardDistance
。我目前对如何处理这些功能以优化它们一无所知(如果可能的话)。寻求你的帮助!
“有问题”作品的参考:
-- | Manhattan distance of a tile at vector index on a board with dimensions n x n
manhattan :: Int -> Int -> Int -> Int
manhattan tile n index = if tile == 0 then 0 else rowDistance + columnDistance
where
(row, column) = v2m n index -- convert vector index to matrix index
rowDistance = abs (row - ((tile - 1) `div` n))
columnDistance = abs (column - ((tile - 1) `mod` n))
-- | Manhattan distance of the entire board
boardDistance :: BoardDimension -> Board -> Int
boardDistance n currentBoard = sum $ map (\index -> manhattan (currentBoard ! index) n index) [0..n*n-1]
答案 0 :(得分:-2)
看看这种解决方案的类型,我怀疑很多你的性能损失来自于免费monad的糟糕表现(Maybe
是一个免费的monad)。这是codensity transformation将成为胜利的一个主要例子。或者,您可以使用专为组合搜索而设计的monad,例如logict。