【问题标题】:Returning neighbours of a cell in a given matrix F#返回给定矩阵 F# 中单元格的邻居
【发布时间】:2014-12-20 06:19:14
【问题描述】:

我写了一个小的 sn-p 用于提取 NxN 矩阵中给定单元的任何邻居。像这样

let getNeighbours (x,y) (matrix: 'a [,]) = 
    let lower n = max 0 (n - 1)
    let upper n = min (matrix.GetUpperBound(0)) (n + 1)
    matrix.[lower x..upper x, lower y..upper y]

val arr : int [,] = [[29; 42; 0; 46; 55; 79; 18; 8]
                     [94; 25; 20; 45; 88; 73; 51; 69]
                     [62; 38; 66; 21; 55; 30; 37; 95]
                     [13; 35; 91; 0; 80; 15; 81; 22]
                     [2; 45; 94; 28; 50; 50; 35; 64]
                     [67; 98; 94; 63; 32; 11; 83; 23]
                     [38; 71; 31; 45; 52; 20; 20; 98]
                     [5; 4; 33; 19; 87; 17; 28; 78]]

> getNeighbours (4,0) arr;;
val it : int [,] = [[13; 35]
                    [2; 45]
                    [67; 98]]

现在它按预期工作了,我对 F# Interactive 显示 2D 数组的方式有点不满意(它会翻转它们,因此 X 轴将垂直显示,而 Y 轴将水平显示)但除了没有投诉。

但是我无法弄清楚如何以简洁的方式从邻居中排除给定的单元格,假设矩阵中每个单元格的值可以保持相同的值,因此是给定单元格的唯一唯一标识符将是它的索引。

【问题讨论】:

    标签: matrix f# neighbours


    【解决方案1】:

    这是另一种方法,基于您提出的解决方案,但使用 sequence expressions

    let getNeighbours (x,y) (matrix: 'a [,]) = 
        let lower n = max 0 (n - 1)
        let upper n = min (matrix.GetUpperBound(0)) (n + 1)
        seq {
            for i = lower x to upper x do
                for j = lower y to upper y do
                    if (i, j) <> (x, y) then
                        yield matrix.[i, j]}
    

    【讨论】:

    • 我非常喜欢这个解决方案,很好!
    【解决方案2】:

    我最终采用的方法是将数组展平,将其转换为地图并删除给定单元格的第一次出现。它不像我希望的那样简洁或漂亮,也许其他人会有更好的解决方案。

    let getNeighbours (x,y) (matrix: 'a [,]) = 
        let flatten (arr: ((int * int) * 'a) [,]) = 
            arr |> Seq.cast<((int * int) * 'a)>
        let lower n = max 0 (n - 1)
        let upper n = min (matrix.GetUpperBound(0)) (n + 1)
        let hmap = matrix.[lower x..upper x, lower y..upper y] 
                   |> Array2D.mapi (fun i j value -> ((i,j), value))
                   |> flatten
                   |> Map.ofSeq
        hmap.Remove (Map.findKey (fun key value -> value = matrix.[x, y]) hmap)
        |> Map.fold (fun acc _ value -> acc |> List.append [value]) []
    

    【讨论】:

      猜你喜欢
      • 2014-12-14
      • 1970-01-01
      • 1970-01-01
      • 2019-05-26
      • 1970-01-01
      • 2016-04-06
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多