def inits = { list -> (0..<list.size()).collect { list[0..it] } } def tails = { list -> (0..<list.size()).collect { list[it..list.size()-1] } } //lose def keyword to support recursion. weird. traverse = {isLeaf, collection -> if (isLeaf(collection)) return collection return traverse(isLeaf, traverse(isLeaf, collection.head()) + traverse(isLeaf, collection.tail())) } def isPrimitiveList = { if (!it) return true if (!(it instanceof Collection)) return false if (it.head() instanceof Collection) { if (it.head().head() instanceof Collection) return false } true } def flatten = traverse.curry(isPrimitiveList) def segs = { list -> flatten(inits(list).collect { tails(it) }) } def sum = { list -> list.collect { it.sum() } } def solve = { list -> sum(segs(list)).max() } def numbers = [31,-41,59,26,-53,58,97,-93,-23,84] def solution = solve(numbers) println "Maximum Segment Sum of $numbers is $solution" |
#light // turns off some OCaml
syntax let rec inits list = let length = List.length list List.init length (fun i -> Seq.take (i+1) list ) let tails list = inits (List.rev list) // Groovy lacks a map_concat function, which F# has // This means Groovy required a custom flatten // method to flatten a "list of lists of lists" to a // "list of lists". +1 for F# having better list functions. let segs list = List.map_concat (fun e -> tails e) (inits list) let sum list = let sumElement e = List.fold_left (+) 0 e List.map sumElement list let solve list = List.reduce_left (max) (sum (segs list)) let numbers = [31;-41;59;26;-53;58;97;-93;-23;84] let solution = solve numbers printfn "Maximum Segment Sum of %A is %d" numbers solution |