我正在學習思考和編碼haskell。 「最小數字贏」比賽:n人對1到n之間的數字進行投注,而只有一次下注的最小數字贏得比賽。計算所有可能遊戲的「最小數量獲勝」遊戲結果 - 內存不足
我正在計算n = 10的所有可能的投注系列並計算贏家數字。是的,這段代碼並不完全是這樣,但那不是我的觀點,而是我的代碼,它的內存耗盡速度相對較快。
(添加的註釋 - !對不起)
import Data.Array
import Data.List
f xs = flip map [1..10] $ flip (:) xs
p 1 = f []
p n = concat $ map f $ p (n-1)
--the above, (p n) generates the list of all possible [a1, a2, ..., an] lists, where ai=1..10
--p 2 = [[1,1],[2,1],[3,1],[4,1],[5,1],...,[10,10]
--my first shot at the countidens function, the functionality stays the same with the other
--countidens2 xs = map (\x->(head x, length x)) $ group $ sort xs
countidens' xs = accumArray (+) 0 (1,10) $ zip xs $ repeat 1
countidens xs = filter ((/=) 0 . snd) $ zip [1..10] $ map ((countidens' xs)!) [1..10]
--counts the number of occurrences of each number (1..10) in a list
--countidens [1,1,1,2,2,3] = (1,3),(2,2),(3,1)]
--(the above, countidens2 is much easier to understand)
numlist n = map (flip (++) ([(0,0)])) $ map countidens $ p n
--maps countidens on the (p n) list, and attaches a dummy (0,0) to the end (this is needed later)
g (x, (y, z)) | (x==y) && (z==1) = True
| (x < y) = True
| (y==0) = True
| otherwise = False
-- filter function for [(a, (a,a)] lists - (a1, (a1, a)) -> Bool
winners n = map fst $ map (head . filter g) $ map (zip [1..]) $ numlist n
-- extracts the number of the first element of (numlist n) that qualifies as g
-- for each element of g (note: these are results of the countidens function, since that was mapped)
-- the dummy (0,0) was needed so there's always one that does
winnernumsarr n = accumArray (+) 0 (1,10) $ flip zip (repeat 1) $ winners n
-- winners n produces a simple list of integers (1..10) that is 10^n long, this (winnernumsarr) accumulates the number of each integer, much like countidens did
-- (but does not produce a fancy output)
main = putStrLn $ show $ winnernumsarr 7 -- aiming for 10! even 8 runs out of memory on my machine
雖然我知道這個代碼沒有做,我想它做什麼,什麼是更重要的是,這不是我第一次遇到haskell的「內存不足」問題,並且我知道的問題可能會用C++編寫,並且只使用少量內存。
必須有一種方式 - 但如何?
如果你用類型註釋每個函數,並給它一個註釋來描述它應該做什麼,這可能會有所幫助 – 2012-03-12 20:02:37