我想用F#解决这个练习:http://code.google.com/codejam/contest/351101/dashboard#s=p0。
我是函数式编程和F#的新手,但我非常喜欢这个概念和语言。而且我喜欢codejam练习,它看起来很容易,但现实生活。有人能指出我的解决方案吗?
目前我已经编写了这个代码,这个代码很简单,从功能角度来说看起来很难看:
(*
C - Credit
L - Items
I - List of Integer, wher P is single integer
How does the data look like inside file
N
[...
* Money
* Items in store
...]
*)
let lines = System.IO.File.ReadAllLines("../../../../data/A-small-practice.in")
let CBounds c = c >= 5 && c <= 1000
let PBounds p = p >= 1 && p <= 1000
let entries = int(lines.[0]) - 1
let mutable index = 1 (* First index is how many entries*)
let mutable case = 1
for i = 0 to entries do
let index = (i*3) + 1
let C = int(lines.[index])
let L = int(lines.[index+1])
let I = lines.[index+2]
let items = I.Split([|' '|]) |> Array.map int
// C must be the sum of some items
// Ugly imperative way which contains duplicates
let mutable nIndex = 0
for n in items do
nIndex <- nIndex + 1
let mutable mIndex = nIndex
for m in items.[nIndex..] do
mIndex <- mIndex + 1
if n + m = C then do
printfn "Case #%A: %A %A" case nIndex mIndex
case <- case + 1
我想找出与C值相加的项目,但不是通常的命令式方法 - 我想要功能性方法。
答案 0 :(得分:4)
您没有指定如何解决问题,因此很难提供建议。
关于阅读输入,您可以将其表达为Seq
上的一系列转换。来自Seq module的高阶函数非常方便:
let data =
"../../../../data/A-small-practice.in"
|> System.IO.File.ReadLines
|> Seq.skip 1
|> Seq.windowed 3
|> Seq.map (fun lines -> let C = int(lines.[0])
let L = int(lines.[1])
let items = lines.[2].Split([|' '|]) |> Array.map int
(C, L, items))
<强>更新强>
对于您的示例的其余部分,您可以使用sequence expression。它功能足够且易于表达嵌套计算:
let results =
seq {
for (C, _, items) in data do
for j in 1..items.Length-1 do
for i in 0..j-1 do
if items.[j] + items.[i] = C then yield (i, j)
}
Seq.iteri (fun case (i, j) -> printfn "Case #%A: %A %A" case i j) results