Skip to content

Instantly share code, notes, and snippets.

@chris-taylor
Created June 23, 2015 09:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chris-taylor/9fdb11b66c09928232eb to your computer and use it in GitHub Desktop.
Save chris-taylor/9fdb11b66c09928232eb to your computer and use it in GitHub Desktop.
scrappy code to find (n,k,t) designs with greedy algorithm
select [] = []
select (x:xs) = (x,xs) : select xs
pairs nums = [(a, b) | (a, bs) <- select nums, b <- bs]
triples nums = [(a,b,c) | (a,bs) <- select nums, (b,cs) <- select bs, c <- cs]
overlap (a,b,c) (d,e,f) =
case compare a d of
LT -> case compare b d of
LT -> False
EQ -> c == e || c == f
GT -> b == e && c == f
EQ -> case compare b e of
LT -> c == e || c == f
EQ -> True
GT -> b == f || c == f
GT -> case compare a e of
LT -> b == e && c == f
EQ -> b == f || c == f
GT -> False
fact n = go 1 n
where
go acc 1 = acc
go acc n = go (acc * n) (n - 1)
nchoosek :: Integer -> Integer -> Integer
nchoosek n k = fact n `div` (fact k * fact (n - k))
solution nums = helper sz nums
where
n = toInteger (length nums)
k = 3
sz = nchoosek n 2 `div` nchoosek 3 2
helper :: Integer -> [Int] -> Maybe [(Int,Int,Int)]
helper sz nums = go 0 [] (triples nums)
where
go _ acc [] = Nothing
go n acc (t:ts) =
if (n == sz)
then Just (reverse acc)
else if any (overlap t) acc
then go n acc ts
else go (n+1) (t:acc) ts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment