Skip to content

Instantly share code, notes, and snippets.

@Denommus
Created March 11, 2015 22:23
Show Gist options
  • Save Denommus/51f74eb0992d6c2abc14 to your computer and use it in GitHub Desktop.
Save Denommus/51f74eb0992d6c2abc14 to your computer and use it in GitHub Desktop.
import Data.Maybe
import Prelude hiding (drop, head, tail, (++), mapM_, zip, length, null)
import Data.Vector
import qualified Data.List as L
import System.Environment
import Control.Applicative
calculate :: (Int, Int, Vector Int) -> (Int, Int)
calculate (c, _, vec) = aux 0
where aux i = let p = vec ! i in
let ps = drop (i+1) vec in
let index = findIndex (\x -> x+p==c) ps in
if isJust index then (i+1, 2+i+fromJust index)
else aux (i+1)
parse :: Vector String -> Vector (Int, Int, Vector Int)
parse vec
| null vec = Data.Vector.empty
| otherwise = let c = vec ! 0 in
let i = vec ! 1 in
let ps = vec ! 2 in
let end = drop 3 vec in
singleton (read c, read i, read <$> fromList (words ps)) ++ parse end
main :: IO ()
main = do
fileName <- L.head <$> getArgs
contents <- fromList <$> lines <$> readFile fileName
let result = calculate <$> parse (tail contents)
mapM_ (\(i, (x, y)) ->
putStrLn $ "Case #" L.++ show (i+1) L.++ ": " L.++ show x L.++ " " L.++ show y) $
imap (,) result
return ()
module Option =
struct
let is_some = function
| Some _ -> true
| None -> false
let from_some = function
| Some a -> a
| None -> raise Not_found
end
open Array
let last arr = get arr (length arr - 1)
let drop i arr = sub arr i (length arr - i)
let find_index f arr =
let index = ref None in
iteri (fun i a -> if f a then index := Some i) arr;
!index
let calculate c i vec =
let rec aux i =
let p = get vec i in
let ps = drop (i+1) vec in
let index = find_index (fun x -> x+p=c) ps in
if Option.is_some index then (i+1, 2+i+Option.from_some index)
else aux (i+1) in
aux 0
let () =
let file_name = last Sys.argv in
let file = open_in file_name in
try
let _ = input_line file |> int_of_string in
let case = ref 0 in
while true do
let c = input_line file |> int_of_string in
let i = input_line file |> int_of_string in
let ps = input_line file |> Str.split (Str.regexp " ") |> Array.of_list |> map int_of_string in
let (x, y) = calculate c i ps in
case := !case+1;
Printf.printf "Case %d: %d %d\n" !case x y
done
with End_of_file ->
close_in file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment