new files
This commit is contained in:
parent
3af7344581
commit
86c034bb8b
1364 changed files with 21352 additions and 0 deletions
17
Task/Knuth-shuffle/Haskell/knuth-shuffle-1.hs
Normal file
17
Task/Knuth-shuffle/Haskell/knuth-shuffle-1.hs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import System.Random
|
||||
import Data.List
|
||||
import Control.Monad
|
||||
import Control.Arrow
|
||||
|
||||
mkRands = mapM (randomRIO.(,)0 ). enumFromTo 1. pred
|
||||
|
||||
replaceAt :: Int -> a -> [a] -> [a]
|
||||
replaceAt i c = let (a,b) = splitAt i l in a++x:(drop 1 b)
|
||||
|
||||
swapElems :: (Int, Int) -> [a] -> [a]
|
||||
swapElems (i,j) xs | i==j = xs
|
||||
| otherwise = replaceAt j (xs!!i) $ replaceAt i (xs!!j) xs
|
||||
|
||||
knuthShuffle :: [a] -> IO [a]
|
||||
knuthShuffle xs =
|
||||
liftM (foldr swapElems xs. zip [1..]) (mkRands (length xs))
|
||||
3
Task/Knuth-shuffle/Haskell/knuth-shuffle-2.hs
Normal file
3
Task/Knuth-shuffle/Haskell/knuth-shuffle-2.hs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
knuthShuffleProcess :: (Show a) => [a] -> IO ()
|
||||
knuthShuffleProcess =
|
||||
(mapM_ print. reverse =<<). ap (fmap. (. zip [1..]). scanr swapElems) (mkRands. length)
|
||||
21
Task/Knuth-shuffle/Haskell/knuth-shuffle-3.hs
Normal file
21
Task/Knuth-shuffle/Haskell/knuth-shuffle-3.hs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import Data.Array.ST
|
||||
import Data.STRef
|
||||
import Control.Monad
|
||||
import Control.Monad.ST
|
||||
import Control.Arrow
|
||||
import System.Random
|
||||
|
||||
shuffle :: RandomGen g => [a] -> g -> ([a], g)
|
||||
shuffle list g = runST $ do
|
||||
r <- newSTRef g
|
||||
let rand range = liftM (randomR range) (readSTRef r) >>=
|
||||
runKleisli (second (Kleisli $ writeSTRef r) >>> arr fst)
|
||||
a <- newAry (1, len) list
|
||||
forM_ [len, len - 1 .. 2] $ \n -> do
|
||||
k <- rand (1, n)
|
||||
liftM2 (,) (readArray a k) (readArray a n) >>=
|
||||
runKleisli (Kleisli (writeArray a n) *** Kleisli (writeArray a k))
|
||||
liftM2 (,) (getElems a) (readSTRef r)
|
||||
where len = length list
|
||||
newAry :: (Int, Int) -> [a] -> ST s (STArray s Int a)
|
||||
newAry = newListArray
|
||||
Loading…
Add table
Add a link
Reference in a new issue