1

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;5;9];
[3;7;0];
]

anybody knows an easy way of doing this in f# ?

H.B.
  • 166,899
  • 29
  • 327
  • 400
Omu
  • 69,856
  • 92
  • 277
  • 407
  • I'm not going to downvote this but if you made any effort to arrive at a solution to this yourself, you should probably let people know what you've done. Right now your question reads "plz give me the codez" whether you meant for it to or not. – Onorio Catenacci Jun 01 '12 at 12:26
  • @OnorioCatenacci I'm sorry, indeed this is what my question is, I can do this in C#, but in F# I just don't know a lot of stuff – Omu Jun 01 '12 at 12:46
  • 2
    @OnorioCatenacci Technically its spelled "plz give me *teh* codez". – J D Jun 01 '12 at 17:35
  • @ChuckNorris See "transpose" http://stackoverflow.com/questions/3016139/help-me-to-explain-the-f-matrix-transpose-function – J D Jun 01 '12 at 17:38
  • @JonHarrop Thanks for teh hedz up. :-P – Onorio Catenacci Jun 01 '12 at 17:41

2 Answers2

5

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])
John Palmer
  • 25,356
  • 3
  • 48
  • 67
  • I was getting some strange `(int -> int -> int32) [,] = [[; ; ; ...` results, changed Array2D.create to Array2D.init and I get the numbers – Omu Jun 01 '12 at 13:06
  • 2
    The first part should be shorten to `let arr = input |> array2D`. – pad Jun 01 '12 at 13:45
4

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.

Be Brave Be Like Ukraine
  • 7,596
  • 3
  • 42
  • 66