Guest User

Untitled

a guest
Jan 23rd, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. import System.Random
  3.  
  4.  
  5. data Direction = Up | Down deriving (Eq)
  6.  
  7.  
  8.  
  9. main :: IO ()
  10. main = do
  11.   let layers = 4
  12.       tries = 10000000
  13.  
  14.   -- infinite list of random integers between 1 and 10 yays. very dirty.
  15.   rs <- (getStdGen >>= (\g -> return $ randomRs (1,10) g)) :: IO [Int]
  16.  
  17.   -- main' returns the number of photons that got through to the other side
  18.   let through = main' rs layers tries 0
  19.  putStrLn $ "Through: " ++ show ( fromIntegral through / fromIntegral tries :: Double )
  20.  
  21.  
  22. main'                         :: (Integral a) => [a] -> a -> a -> a -> a
  23. main' rs layers tries through
  24.  | tries == 0 = through -- if there are zero photons left, then just return the successful ones
  25.  | otherwise =
  26.       if movePhoton rs layers $ (0, Down) -- if the photon got to the other side...
  27.          then main' (tail rs) layers (tries - 1) (through + 1) -- ...make it count.
  28.           else main' (tail rs) layers (tries - 1) through -- otherwise don't.
  29.  
  30.  
  31. -- the empty list case should never occur, it's just their to shut up ghc -Wall
  32. movePhoton                                     :: (Integral a) => [a] -> a -> (a, Direction) -> Bool
  33. movePhoton []     _      _                     = True
  34. movePhoton (r:rs) layers (position, direction)
  35.   | r == 1 && position == 0          && direction == Down = False -- if you're reflecting out into space -- fail.
  36.   | r /= 1 && position == 0          && direction == Up   = False -- if you're going straight into space -- fail.
  37.   | r /= 1 && position == layers - 1 && direction == Down = True -- if you're going straight out on the other side -- success!
  38.  
  39.   -- reflection
  40.   | r == 1 = if direction == Up
  41.                      then movePhoton rs layers (position + 1, Down) -- if you're going up, but reflecting, then go down and reflect.
  42.                      else movePhoton rs layers (position - 1, Up) -- if you're going down, but reflecting, then go up and reflect.
  43.   -- pass through
  44.   | otherwise = if direction == Up
  45.                    then movePhoton rs layers (position - 1, Up) -- if you're going straight up, continue like that.
  46.                    else movePhoton rs layers (position + 1, Down) -- if you're going straight down, continue like that.
Add Comment
Please, Sign In to add comment