Ticket #25: Hailstone.hs

File Hailstone.hs, 1.1 KB (added by Ben Lippmeier, 13 years ago)
Line 
1
2module Main where
3
4import Data.Word
5import Criterion.Main
6import Control.Parallel.Strategies
7import Data.Array.Repa.Index
8import qualified Data.Array.Repa        as R
9import qualified Data.Vector.Unboxed    as V
10
11
12collatzLen :: Word32 -> Word32 -> Word32
13collatzLen c 1 = c
14collatzLen c n | n `mod` 2 == 0 = collatzLen (c+1) $ n `div` 2
15               | otherwise      = collatzLen (c+1) $ 3*n+1
16
17pmax :: Word32 -> Word32 -> Word32
18pmax x n = x `max` collatzLen 1 n
19
20solveAll :: Int -> Int -> Word32
21solveAll step n
22  = foldl max 1 . parMap r0 solve $ zip steps (tail steps)
23  where
24    steps            = [2, 2 + fromIntegral step .. fromIntegral n]
25    solve (from, to) = foldl pmax 1 [from..to]
26
27
28-- Solutions
29-- ---------
30
31strat :: Int -> Word32
32strat n =
33  let p = 100   -- chunk size
34  in  solveAll (n `div` p) n
35
36repa :: Int -> Word32
37repa n = R.foldAll max 1
38       . R.map (collatzLen 1)
39       . R.fromVector (Z:.n-2)
40       $ V.enumFromN 2 (n-2)
41
42
43-- Main
44-- ----
45
46main :: IO ()
47main = defaultMain
48  [ bgroup "hailstone" [ bench "strat" $ nf strat 1000000
49                       , bench "repa"  $ nf repa  1000000 ]
50  ]
51