F # swap elements in Array2D

If I have a 2D array like

test = array2D [|[|1; 2; 3|];
                 [|4; 5; 6|];]

and I want to swap two elements so that, for example,

swap test (0,0) (1,1) //[|[|5; 2; 3|];
                        //[|4; 1; 6|];]

How would I write this? I have seen solutions that pass each element by reference and mutate it, but to me it seems to be monotonous (I could be wrong).

+4
source share
2 answers

You can write a swap function using Array2D.mapi , which does not modify the original array. This will return a new array with the changed values:

let swap (arr : int[,]) i1 i2 =
    let map i j v =
        match (i,j) with
        | t when t = i1 -> arr.[fst i2, snd i2]
        | u when u = i2 -> arr.[fst i1, snd i1]
        | _ -> v
    arr |> Array2D.mapi map
+3
source

Here is a simple exchange in place.

module Array2D =
    let swap (x1, y1) (x2, y2) (array: _[,]) =
        let temp = array.[x1, y1]
        array.[x1, y1] <- array.[x2, y2]
        array.[x2, y2] <- temp
        array

If you want a copy, just insert the call Array2D.copy:

array2D [|[|1; 2; 3|];[|4; 5; 6|]|]
|> Array2D.copy
|> Array2D.swap (0,0) (1,1) 
|> printfn "%A"
+3
source

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


All Articles