Skip to content

Instantly share code, notes, and snippets.

@gallais
Last active August 29, 2015 14:11
Show Gist options
  • Save gallais/72d425888da92b44a57e to your computer and use it in GitHub Desktop.
Save gallais/72d425888da92b44a57e to your computer and use it in GitHub Desktop.
Partition
module Partition where
import Data.Function.Memoize
type Target = Int
type Digits = Int
type MaxInt = Int
partitionMaxBrute :: Digits -> Target -> MaxInt -> [[Int]]
partitionMaxBrute d t m
| d == 0 && t == 0 = [[]]
| d * m < t || m <= 0 = []
| t < m = partitionMaxBrute d t (t + 1 - d)
| otherwise = partitionMaxBrute d t (m - 1)
++ fmap (m :) (partitionMaxBrute (d - 1) (t - m) m)
partitionBrute :: Digits -> Target -> [[Int]]
partitionBrute d t = partitionMaxBrute d t (t + 1 - d)
partitionMax :: (Digits -> Target -> MaxInt -> [[Int]]) ->
Digits -> Target -> MaxInt -> [[Int]]
partitionMax rec d t m
| d == 0 && t == 0 = [[]]
| d * m < t || m <= 0 = []
| t < m = rec d t (t + 1 - d)
| otherwise = rec d t (m - 1)
++ fmap (m :) (rec (d - 1) (t - m) m)
partition :: Digits -> Target -> [[Int]]
partition d t = memoPM d t (t + 1 - d)
where memoPM = memoize3 $ partitionMax memoPM
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment