Created
February 26, 2013 00:44
-
-
Save tarrsalah/5034773 to your computer and use it in GitHub Desktop.
solution the RopeInternet google codejam problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* solving the rope internet problem *) | |
exception Error | |
val min = Int.min | |
val inFile= TextIO.stdIn | |
val outFile= TextIO.stdOut | |
fun new_node (n1,n2) l = | |
(* how many nodes did this tuple introduce to the problem *) | |
case l of | |
[] => 0 | |
| (x1, x2)::xs => (if ( x1 > n1 andalso x2 < n2) orelse (x1 < n1 andalso x2 > n2) then 1 else 0) + (new_node (n1,n2) xs) | |
fun solveCase l= | |
case l of | |
[] => 0 | |
| (w1,w2)::ws => solveCase ws + (new_node (w1,w2) l) | |
val solve = List.map solveCase (* cases *) | |
fun sti s= | |
(* string ==> SML Int *) | |
let | |
val ss =String.map (fn x => if x = #"-" then #"~" else x) s | |
in | |
case Int.fromString ss of | |
NONE => raise Error | |
| SOME i => i | |
end | |
fun getLine inFile= | |
case (TextIO.inputLine inFile) of | |
NONE => "" | |
| SOME line => line | |
val getWords = String.tokens (fn x => (x = #" ") orelse (x = #"\n") orelse (x= #"\t")) | |
fun list_to_tuple l= | |
case l of | |
[x1,x2] => (x1,x2) | |
| _ => raise Error | |
val getOneint = sti o getLine | |
fun parseIn inFile= | |
(* get the cases from the input *) | |
let | |
val T = getOneint inFile | |
fun getCase inFile n= | |
(* take how many windows in the case | |
and return a list of tuples *) | |
if n = 0 | |
then [] | |
else list_to_tuple (List.map sti (getWords (getLine inFile)))::(getCase inFile (n -1)) | |
fun getCases inFile n= | |
if n = 0 | |
then [] | |
else (getCase inFile (getOneint inFile))::(getCases inFile (n - 1 )) | |
in | |
getCases inFile T | |
end | |
fun parseOut f solutions outFile= | |
(* parse a solutions to the output, using f to parse every solution in the list *) | |
let | |
fun getStringFrom i0 solutions = | |
case solutions of | |
[] => "" | |
| r::[] => "Case #" ^ (Int.toString i0) ^ ": " ^ (f r) ^ "\n" | |
| r::rs => "Case #" ^ (Int.toString i0) ^ ": " ^ (f r) ^ "\n" ^ (getStringFrom (i0 + 1) rs) | |
val _ = TextIO.output (outFile, getStringFrom 1 solutions) | |
in | |
() | |
end | |
val _ = parseOut Int.toString (solve (parseIn inFile)) outFile |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment