当前位置: 首页>>代码示例>>C#>>正文


C# Trie.GetOrDefault方法代码示例

本文整理汇总了C#中Trie.GetOrDefault方法的典型用法代码示例。如果您正苦于以下问题:C# Trie.GetOrDefault方法的具体用法?C# Trie.GetOrDefault怎么用?C# Trie.GetOrDefault使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Trie的用法示例。


在下文中一共展示了Trie.GetOrDefault方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

    /* 3 Write a program that finds a set of words (e.g. 1000 words)
     * in a large text (e.g. 100 MB text file). Print how many times
     * each word occurs in the text.
     * Hint: you may find a C# trie in Internet.
     * */
    static void Main(string[] args)
    {
        var dict = new Dictionary<string, int>();
        var knownCount = new Dictionary<string, int>
        {
            {"foo", 10*1000},
            {"bar", 20*1000},
            {"quux",30*1000},
            {"frob",40*1000},
            {"asdf",50*1000}
        };
        var trie = new Trie<int>();

        var sw = new Stopwatch();

        sw.Start();

        // obviously, I couldn't zip the 100 MB file
        // use "bin\debug\generator.cs" to generate it if you want

        using (var reader = new StreamReader("text.txt"))
            foreach (var word in Words(reader))
                dict[word] = 1 + dict.GetOrDefault(word, 0);

        sw.Stop();
        /*
        foreach (var kvp in knownCount)
            Debug.Assert(dict[kvp.Key] == kvp.Value);
        */

        Console.WriteLine("Using hashtable: " + sw.Elapsed.TotalMilliseconds);

        sw.Reset();
        sw.Start();

        using (var reader = new StreamReader("text.txt"))
            foreach (var word in Words(reader))
                trie.Add(word, 1 + trie.GetOrDefault(word, 0));

        sw.Stop();

        foreach (var kvp in dict)
            Debug.Assert(trie.Find(kvp.Key) == kvp.Value);

        // the trie would probably do much better compared to a hashtable when used on
        // natural text with large amount of repetition and low average word length
        // it is however extremely space inefficient

        // at any rate, I'd be surprised if this implementation could beat .NET's build-in
        // hashtable

        Console.WriteLine("Using trie: " + sw.Elapsed.TotalMilliseconds);
    }
开发者ID:staafl,项目名称:ta-hw-dsa,代码行数:58,代码来源:program.cs


注:本文中的Trie.GetOrDefault方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。