Skip to content

Instantly share code, notes, and snippets.

@jgcoded
Last active August 29, 2015 14:21
Show Gist options
  • Save jgcoded/957f59cbded3b78b4ae8 to your computer and use it in GitHub Desktop.
Save jgcoded/957f59cbded3b78b4ae8 to your computer and use it in GitHub Desktop.
Defines a function nCombination which generates and prints out all n-combinations as a list. Uses Data.IntSet.
import Control.Monad (unless)
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
-- Generate and print out all combinations up to size n
nCombination :: Int -> IO ()
nCombination n = do
print $ IntSet.toList IntSet.empty
combination' n IntSet.empty $ makeBaseCase n
-- create the base case for the combination algorithm
makeBaseCase :: Int -> IntSet.IntSet
makeBaseCase 0 = IntSet.empty
makeBaseCase n = IntSet.insert n $ makeBaseCase (n-1)
{- prints out all n combinations
use it like this:
combination 8 IntSet.empty $ makeBaseCase 8
-}
combination' :: Int -> IntSet.IntSet -> IntSet.IntSet -> IO ()
combination' n xs bs = do
let nextxs = nextIntSet n xs
print $ IntSet.toList nextxs
unless (nextxs == bs) $ combination' n nextxs bs
-- get the first element from the right that is not in the set
findN :: Int -> IntSet.IntSet -> Int
findN 0 _ = 0
findN n xs = if not (IntSet.member n xs)
then n
else findN (n-1) xs
-- removes all values from x+1 to n in the IntSet
removeUpToN :: Int -> Int -> IntSet.IntSet -> IntSet.IntSet
removeUpToN x n xs
| x > n = xs
| otherwise = removeUpToN (x+1) n $ IntSet.delete (x+1) xs
-- Generate the next IntSet
nextIntSet :: Int -> IntSet.IntSet -> IntSet.IntSet
nextIntSet n xs = removeUpToN x n $ IntSet.insert x xs
where
x = findN n xs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment