Array2D to array

I have Array2D of 0 and 1:

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

I need to calculate the number 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 convert Array2D to Array?

+6
source share
2 answers

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

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

but if you only need an account you can make

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

since conditions 0 will not be added to the amount, and the members you want to calculate are only 1

+6
source

The function converted from Array2D to Array is very convenient in many situations.

You can save it in the Array2D module for ease of use.

 module Array2D = let toArray (arr: 'T [,]) = arr |> Seq.cast<'T> |> Seq.toArray 
+6
source

Source: https://habr.com/ru/post/927622/


All Articles