Code Golf: Decision Tree

Viewed 7899

In Google Code Jam 2009, Round 1B, there is a problem called Decision Tree that lent itself to rather creative solutions.

Post your shortest solution; I'll update the Accepted Answer to the current shortest entry on a semi-frequent basis, assuming you didn't just create a new language just to solve this problem. :-P

Current rankings:

23 Answers

m4 with echo and bc, 339 bytes

This solution is a complete and utter hack, and it gives me a headache. It contains, among other things, escaped double quotes, unescaped double quotes, unescapable backquote and single quote pairs (including a nested pair seven quotes deep), unquoted regular expressions, outsourcing decimal multiplication to bc, and the use of craZy caSE to circumvent macro expansion. But it had to be done, I guess. :p

This adds an "ultimate macroizing" solution to the previous kinds of solutions (iterated loops, recursion w/ lambda mapping, labels and branches, regexp and eval, etc.)

I think a good term for this is "macroni code" :D

(wrapped every 60 characters, for clarity)

define(T,`translit($@)')define(Q,`patsubst($@)')define(I,0)Q
(T(T(T(Q(Q(Q(Q(Q(Q(T(include(A),(),<>),>\s*>,>>),>\s*<,>;),\
([a-z]+\)\s*<,`*ifElsE<rEgExp<P;``````` \1 ''''''';0>;0;<'),
^<,`defiNe<````I';iNcr<I>>\\"Case `#'I:\\"defiNe<`A'''';'),^
[0-9]*),.+ [0-9]+.*,`dEfiNE<```P';`\& '''>A'),<>;N,`(),n'),E
,e),()),.*,`syscmd(`echo "\&"|bc -l')')

Usage: $ cp input.in A; m4 thisfile.m4 > output.out

I'm an m4 n00b, though, having learned it only an hour before writing this. So there's probably room for improvement.

F#: 759 significant chars (Wow, I'm bad at this ;) )

Minimized version

open System.Text.RegularExpressions
type t=T of float*(string*t*t)option
let rec e=function x,T(w,Some(s,a,b))->e(x,if Set.contains s x then a else b)*w|x,T(w,_)->w
let rec h x=Regex.Matches(x, @"\(|\)|\d\.\d+|\S+")|>Seq.cast<Match>|>Seq.map (fun x -> x.Value)|> Seq.toList
let rec p=function ")"::y->p y|"("::w::x::y->match x with ")"->T(float w,None),y|n->let a,f=p y in let b,g=p f in T(float w,Some(n,a,b)),g
let solve input =
    Regex.Matches(input,@"(\(((?<s>\()|[^()]|(?<-s>\)))*\)(?(s)(?!)))\s+\d+\s+((\S+\s\d(.+)?\s*)+)")
    |>Seq.cast<Match>
    |>Seq.map(fun m->fst(p(h(m.Groups.[1].Value))), [for a in m.Groups.[3].Value.Trim().Split([|'\n'|])->set(a.Split([|' '|]))])
    |>Seq.iteri(fun i (r,c)->printfn"Case #%i"(i+1);c|>Seq.iter(fun x->printfn"%.7F"(e(x, r))))

Readable version

open System.Text.RegularExpressions

type decisionTree = T of float * (string * decisionTree * decisionTree) option
let rec eval = function 
    | x, T(w, Some(s, a, b)) -> eval(x, if Set.contains s x then a else b) * w
    | x, T(w, _) -> w

// creates a token stream
let rec tokenize tree =
    Regex.Matches(tree, @"\(|\)|\d\.\d+|\S+")
    |> Seq.cast<Match>
    |> Seq.map (fun x -> x.Value)
    |> Seq.toList

// converts token stream into a decisionTree
let rec parse = function
    | ")"::xs -> parse xs
    | "("::weight::x::xs ->
        match x with
        | ")" -> T(float weight, None), xs
        | name ->
            let t1, xs' = parse xs
            let t2, xs'' = parse xs'
            T(float weight, Some(name, t1, t2)), xs''

// uses regex to transform input file into a Seq<decisionTree, list<set<string>>, which each item in our 
// list will be tested against the decisionTree
let solve input =
    Regex.Matches(input, @"(\(((?<s>\()|[^()]|(?<-s>\)))*\)(?(s)(?!)))\s+\d+\s+((\S+\s\d(.+)?\s*)+)")
    |> Seq.cast<Match>
    |> Seq.map (fun m -> fst(parse(tokenize(m.Groups.[1].Value))), [for a in m.Groups.[3].Value.Trim().Split([|'\n'|]) -> set(a.Split([|' '|])) ])
    |> Seq.iteri (fun i (tree, testCases) ->
            printfn "Case #%i" (i+1)
            testCases |> Seq.iter (fun testCase -> printfn "%.7F" (eval (testCase, tree)))
        )
Related