Difference between revisions of "Google Code Jam/Saving The Universe"

From HaskellWiki
Jump to navigation Jump to search
 
Line 1: Line 1:
  +
We can solve it in one run through the list of queries, threading a list of servers with the run. The list of servers is updated deleting them as they appear in the query list. Whenever we find ourself with only one server we drop all the queries that are still possible. If we are left no queries that was the last server used , so we mark no changes, otherwise we keep processing the rest of the list with a fresh list of servers.
  +
To be noted, there are two base cases for the recursion. I hope someone can recode this.
  +
  +
 
<hask>
 
<hask>
 
import Data.List
 
import Data.List

Revision as of 16:03, 18 July 2008

We can solve it in one run through the list of queries, threading a list of servers with the run. The list of servers is updated deleting them as they appear in the query list. Whenever we find ourself with only one server we drop all the queries that are still possible. If we are left no queries that was the last server used , so we mark no changes, otherwise we keep processing the rest of the list with a fresh list of servers. To be noted, there are two base cases for the recursion. I hope someone can recode this.


import Data.List rcount :: Eq a => [a] -> [a] -> Integer rcount names qs = count names qs where count _ [] = 0 count [n] qs = let qs' = dropWhile (/= n) qs in if null qs' then 0 else 1 + count names qs' count ns (q:qs) = count (delete q ns) qs parseCase [] = Nothing parseCase (n:xs) = let (ns,q:rs) = splitAt (read n) xs (qs,rs') = splitAt (read q) rs in Just ((ns,qs),rs') type Names = [String] type Queries = [String] parseCases :: String -> [(Names,Queries)] parseCases x = let (n:ts) = lines x in take (read n) . unfoldr parseCase $ ts main = do ts <- parseCases `fmap` getContents flip mapM_ (zip [1..] ts) $ \(i,(ns,qs)) -> do putStr $ "Case #" ++ show i ++ ": " print $ rcount ns qs