【问题标题】:How to create a histogram from a 2d array F#如何从二维数组 F# 创建直方图
【发布时间】:2015-05-30 19:47:00
【问题描述】:

如何在 F# 中从二维数组创建直方图。

我尝试过这样的事情:

let histogram =
    Array.iter (fun acc fs -> 
        fs |> List.iter (fun k -> 
            if Map.containsKey k acc
            then Map.add k (acc.[k] + 1) acc
            else Map.add k 1 acc
        )
    ) Map.empty

但是我真的不知道如何解决这个问题。 有什么建议可以启动我吗?

【问题讨论】:

    标签: arrays f# histogram


    【解决方案1】:

    如果我没看错的话:

    let arr = [| [|1; 2; 4 |] ;[|3; 2; 4 |] ;[|1; 7; 4 |] |]
    arr |> Array.concat |> Array.sort |> Seq.groupBy id |> Seq.map(fun el -> fst el,Seq.length (snd el)) 
    |> Seq.iter(fun x -> printfn "%d [%d]" (fst x) (snd x)))
    

    输出:

    1 [2]
    2 [2]
    3 [1]
    4 [3]
    7 [1]
    

    http://ideone.com/P5hmtU

    【讨论】:

    • FWIW,您可以将 Seq.groupBy id |> Seq.map(fun el -> fst el,Seq.length (snd el)) 替换为 Seq.countBy id
    • kaefer,谢谢。您的变体要好得多
    • Can't quiet get it to work, but just found that format is like, a list of arrays: [2; 19] [3; 13] [2; 2; 2; 5] [41] [2; 3; 7] [43] [2; 2; 11] [3; 3; 5] [2; 23] [47]
    • 解决了这个问题:arr |> List.concat |> List.sort |> Seq.countBy id。感谢您的帮助!
    猜你喜欢
    • 2018-04-16
    • 2021-01-17
    • 2015-01-25
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 2016-09-06
    • 2012-11-10
    • 1970-01-01
    相关资源
    最近更新 更多