Advertisement
Guest User

Fast Solve

a guest
Jan 22nd, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. fastSolve :: [Int] -> Bool
  2. fastSolve xs = interpret (accSolve Nothing Nothing Nothing Nothing xs)
  3.  
  4. rEven, rOdd, rSmall :: Int -> Bool
  5. rEven  x = x `mod` 2 == 0
  6. rOdd   x = x > 0 && x `mod` 2 == 1
  7. rSmall x = 5 <= x && x <= 10
  8.  
  9. -- shortcut for types
  10. type M a = Maybe a
  11.  
  12. accSolve :: M Int -> M Int -> M Int -> M Int -> [Int] -> (M Int, M Int, M Int, M Int)
  13. accSolve sE sO bE bO []     = (sE,sO,bE,bO)
  14. accSolve sE sO bE bO (x:xs) = case (rSmall x, rEven x, rOdd x) of
  15.   (True, True, False) -> case sE of
  16.                            Nothing  -> accSolve (Just x) sO bE bO xs
  17.                            (Just y) -> accSolve sE sO (Just x) bO xs
  18.   (True, False, True) -> case sO of
  19.                            Nothing  -> accSolve sE (Just x) bE bO xs
  20.                            (Just y) -> accSolve sE sO bE (Just x) xs
  21.  
  22.   (False, True, False) -> accSolve sE sO (Just x) bO xs
  23.   (False, False, True) -> accSolve sE sO bE (Just x) xs
  24.  
  25.   (False, False, False) -> accSolve sE sO bE bO xs
  26.  
  27. interpret :: (M Int   , M Int   , M Int   , M Int   ) -> Bool
  28.  
  29. interpret    (Just jsE, _       , Just jbE, Just jbO) = True
  30. interpret    (_       , Just jsO, Just jbE, Just jbO) = True
  31.  
  32. interpret    (Just jsE, Just jsO, _       , Just jbO) = True
  33. interpret    (Just jsE, Just jsO, Just jbE, _       ) = True
  34.  
  35. interpret    (_       , _       , _       , _       ) = False
  36.  
  37. {-
  38.  
  39. This exploits the fact that any number that satisfies rSmall will either
  40.     satisfy rOdd or rEven.
  41.  
  42. We use four accumulators abbreviated for convenience:
  43. - smallEven
  44. - smallOdd
  45. - bigEven
  46. - bigOdd
  47.  
  48. small means the number is     inside [5,10]
  49. big   means the number is NOT inside [5,10]
  50. even is obvious
  51. odd refers to those positive and odd
  52. Numbers that don't meet any of these are irrelevant so we can throw them away.
  53.  
  54. We have to hold on to two numbers in [5,10] (nicknamed small) because
  55.     at the end we could need either to fill in for it's more general
  56.     trait. Look at how `interpret` handles cases with both smalls filled.
  57.  
  58. -}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement