Get lists from where each list will contain the elements from a x position from another collection of lists

前端 未结 2 785
太阳男子
太阳男子 2021-01-25 08:47

basically having this:

[
[1;2;3];
[4;5;7];
[8;9;0];
]

I would like to get this (read vertically/ turn 90 degrees):

[
[1;4;8];
[         


        
相关标签:
2条回答
  • 2021-01-25 09:09

    What you need is called matrix transposition.

    PowerPack

    The simplest way is using FSharp.PowerPack; Microsoft.FSharp.Math.Matrix module has Transpose method.

    Simple algorithm

    If you prefer your own solution, here's the one that demonstrates a good combination of short code and executing efficiency:

    let rec transpose = function
        | (_::_)::_ as M -> List.map List.head M :: transpose (List.map List.tail M)
        | _ -> []
    
    // use
    [[1; 2; 3]; [4; 5; 6]; [7; 8; 9]]
    |> transpose
    |> printfn "%A"
    

    In-place matrix transposition

    Yet another approach is in-place matrix transposition. It has complexity of O(n), but requires mutable data.

    0 讨论(0)
  • 2021-01-25 09:28

    I would do it by converting to arrays -

    let arr = input |> List.map (List.toArray) |> List.toArray //a array of arrays
    let out = Array2D.create size1 size2 (fun x y -> arr.[y].[x])
    
    0 讨论(0)
提交回复
热议问题