1 people like it.

Rotate a matrix clockwise

For a given matrix of height H and width W, create a new matrix of height W and width H which is the clockwise rotation of the original matrix.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
let rotateGridBy90DegreesToTheRight grid =
    let height, width = Array2D.length1 grid, Array2D.length2 grid
    Array2D.init width height (fun row column -> Array2D.get grid (height - column - 1) row)
let printGrid width =
    Array2D.iteri (fun _ column item ->
        printf "%d " item
        if column = width - 1 then printfn "")
let height, width = 2, 3
let testGrid = Array2D.init height width (fun row column -> row * width + column)
printGrid width testGrid
printfn ""
rotateGridBy90DegreesToTheRight testGrid |> printGrid height
val rotateGridBy90DegreesToTheRight : grid:'a [,] -> 'a [,]

Full name: Script.rotateGridBy90DegreesToTheRight
val grid : 'a [,]
val height : int
val width : int
module Array2D

from Microsoft.FSharp.Collections
val length1 : array:'T [,] -> int

Full name: Microsoft.FSharp.Collections.Array2D.length1
val length2 : array:'T [,] -> int

Full name: Microsoft.FSharp.Collections.Array2D.length2
val init : length1:int -> length2:int -> initializer:(int -> int -> 'T) -> 'T [,]

Full name: Microsoft.FSharp.Collections.Array2D.init
val row : int
val column : int
val get : array:'T [,] -> index1:int -> index2:int -> 'T

Full name: Microsoft.FSharp.Collections.Array2D.get
val printGrid : width:int -> (int [,] -> unit)

Full name: Script.printGrid
val iteri : action:(int -> int -> 'T -> unit) -> array:'T [,] -> unit

Full name: Microsoft.FSharp.Collections.Array2D.iteri
val item : int
val printf : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printf
val printfn : format:Printf.TextWriterFormat<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.printfn
val height : int

Full name: Script.height
val width : int

Full name: Script.width
val testGrid : int [,]

Full name: Script.testGrid
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/7Wk
Posted:5 years ago
Author:groch
Tags: matrix, 2d array , rotation