Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import System.Random
- data Direction = Up | Down deriving (Eq)
- main :: IO ()
- main = do
- let layers = 4
- tries = 10000000
- -- infinite list of random integers between 1 and 10 yays. very dirty.
- rs <- (getStdGen >>= (\g -> return $ randomRs (1,10) g)) :: IO [Int]
- -- main' returns the number of photons that got through to the other side
- let through = main' rs layers tries 0
- putStrLn $ "Through: " ++ show ( fromIntegral through / fromIntegral tries :: Double )
- main' :: (Integral a) => [a] -> a -> a -> a -> a
- main' rs layers tries through
- | tries == 0 = through -- if there are zero photons left, then just return the successful ones
- | otherwise =
- if movePhoton rs layers $ (0, Down) -- if the photon got to the other side...
- then main' (tail rs) layers (tries - 1) (through + 1) -- ...make it count.
- else main' (tail rs) layers (tries - 1) through -- otherwise don't.
- -- the empty list case should never occur, it's just their to shut up ghc -Wall
- movePhoton :: (Integral a) => [a] -> a -> (a, Direction) -> Bool
- movePhoton [] _ _ = True
- movePhoton (r:rs) layers (position, direction)
- | r == 1 && position == 0 && direction == Down = False -- if you're reflecting out into space -- fail.
- | r /= 1 && position == 0 && direction == Up = False -- if you're going straight into space -- fail.
- | r /= 1 && position == layers - 1 && direction == Down = True -- if you're going straight out on the other side -- success!
- -- reflection
- | r == 1 = if direction == Up
- then movePhoton rs layers (position + 1, Down) -- if you're going up, but reflecting, then go down and reflect.
- else movePhoton rs layers (position - 1, Up) -- if you're going down, but reflecting, then go up and reflect.
- -- pass through
- | otherwise = if direction == Up
- then movePhoton rs layers (position - 1, Up) -- if you're going straight up, continue like that.
- else movePhoton rs layers (position + 1, Down) -- if you're going straight down, continue like that.
Add Comment
Please, Sign In to add comment