Skip to content

Instantly share code, notes, and snippets.

@rdbuf
Last active May 19, 2019 15:39
Show Gist options
  • Save rdbuf/0fc9bb403158aee7a8531b48700e42a1 to your computer and use it in GitHub Desktop.
Save rdbuf/0fc9bb403158aee7a8531b48700e42a1 to your computer and use it in GitHub Desktop.
Beautiful combinatorial search
import Control.Monad
import Data.Function
data Combination = Combination Int Int Int Int
deriving Show
f (Combination x1 x2 x3 x4) = x1 + x2 + x3 - x4 >= 5
comb :: Maybe [Combination]
comb = sequence $ toComb <$> replicateM 4 [1..6] where
toComb [x1,x2,x3,x4] = Just $ Combination x1 x2 x3 x4
toComb _ = Nothing
c :: Integer -> Integer -> Integer
c n k = product [n-k+1..n] `div` product [1..k]
data Straightforward = Straightforward Int deriving Show
data Analytical = Analytical Integer deriving Show
main = do
print $ Straightforward . length . filter f <$> comb
print $ Analytical (c 16 4 - c 4 1 * c 10 4 + c 4 2 * c 4 4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment