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

前端 未结 2 815
太阳男子
太阳男子 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.

提交回复
热议问题