Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array2D to Array

Tags:

f#

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?

like image 626
ceth Avatar asked Oct 13 '12 05:10

ceth


2 Answers

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

like image 142
John Palmer Avatar answered Nov 04 '22 10:11

John Palmer


The function transforming from Array2D to Array is very handy in many situations.

You can keep it in Array2D module for convenient use.

module Array2D =
    let toArray (arr: 'T [,]) = arr |> Seq.cast<'T> |> Seq.toArray
like image 40
pad Avatar answered Nov 04 '22 10:11

pad