Skip to content

Instantly share code, notes, and snippets.

@fffej
Created October 17, 2012 06:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fffej/3904088 to your computer and use it in GitHub Desktop.
Save fffej/3904088 to your computer and use it in GitHub Desktop.
Best first search for factors and multiples
module FactorsAndMultiples where
import Data.List
import Data.Ord (comparing)
isFom :: Int -> Int -> Bool
isFom x y = x `mod` y == 0 || y `mod` x == 0
isSequenceValid :: [Int] -> Bool
isSequenceValid [] = True
isSequenceValid (x:xs) = isSequenceValid' x xs
where
isSequenceValid' _ [] = True
isSequenceValid' n (y:ys) = isFom n y && isSequenceValid' y ys
bruteForce :: [Int] -> [Int]
bruteForce xs = maximumBy (comparing length) (filter isSequenceValid allCombinations)
where
allCombinations = concatMap permutations (subsequences xs)
hn :: Int -> [Int] -> [(Int,[Int])]
hn n xs = map (\x -> (x, chooseNumbers x xs)) xs
where
chooseNumbers z zs= filter (\y -> isFom z y && isFom n z) (delete z zs)
best :: Int -> [Int] ->[(Int,[Int])]
best n xs = sortBy (comparing (length . snd)) (hn n xs)
bestFirstSearch :: Int -> [Int] -> [Int]
bestFirstSearch n xs
| null xs = []
| null choices = []
| otherwise = choice : bestFirstSearch choice (delete choice xs)
where
choices = filter (\(_,x) -> not (null x)) (best n xs)
choice = fst $ head choices
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment