Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Data.Char(digitToInt)
- import Text.Printf
- -- Input => solver => output.
- main = interact (unlines . solve . lines)
- -- Ignore the first line of input (number of test cases).
- solve (_:xs) = solveaux xs 1
- -- Parse the input to the Int and Lists, pass those values to the actual algorithm and parse the solution to a list
- -- of strings.
- solveaux :: [String] -> Int -> [String]
- solveaux [] _ = []
- solveaux (credit:_:items: xs) idx =
- (strSelectedItems (read credit :: Int) $ parseItems items) : solveaux xs (idx + 1)
- where strSelectedItems c is = toResult (selectedItems c is) idx
- -- I could, and probably should, put this in the were clause of the solveaux function.
- toResult :: (Int, Int) -> Int -> String
- toResult (x,y) i = printf "Case #%d: %d %d" i x y
- -- The actual algorithm for the problem.
- selectedItems :: Int -> [Int] -> (Int, Int)
- selectedItems cred items =
- select cred $ comb 2 [1..(length items)]
- where select c [] = (1,1)
- select c ([i1, i2]:ps) = if ((items !! (i1-1)) + items !! (i2-1)) == c
- then (i1, i2)
- else select c ps
- -- There are a few other ways to implement this in http://rosettacode.org/wiki/Combinations#Haskell
- -- but this one seemed to be the most straight forward.
- comb :: Int -> [a] -> [[a]]
- comb 0 _ = [[]]
- comb _ [] = []
- comb m (x:xs) = map (x:) (comb (m-1) xs) ++ comb m xs
- -- "1 2 3" => [1,2,3]
- parseItems :: String -> [Int]
- parseItems is = map readint (words is)
- where readint x = read x :: Int
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement