Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

f# - Array2D to Array

I have Array2D of 0 and 1:

let rnd = System.Random()
let a = Array2D.init n n (fun i j  -> int(System.Math.Round(rnd.NextDouble() / index)) )

I need to calculate the count of '1'-elements, something like:

a |> Array.filter (fun x -> x == 1)

But 'a' is Array2D (not Array) so I'm just wondering if there is a standard way to transform Array2D to Array?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is one easy way, using the fact that [,] implements ienumerable<_>

a |> Seq.cast<int> |> Seq.filter (fun x -> x == 1)

but if you only need the count you can do

a |> Seq.cast<int> |> Seq.sum

as the 0 terms won't add to the sum and the terms you want to count are just 1


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...