Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Anagrams.cs « UserGuideExamples « Mono.C5 « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 64ca20f515fa77270b7832d69a8c85325754c688 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
/*
 Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
*/

// C5 example: anagrams 2004-08-08, 2004-11-16

// Compile with 
//   csc /r:C5.dll Anagrams.cs 

using System;
using System.IO;                        // StreamReader, TextReader
using System.Text;			// Encoding
using System.Text.RegularExpressions;   // Regex
using C5;
using SCG = System.Collections.Generic;

namespace Anagrams
{
  class MyTest
  {
    public static void Main(String[] args)
    {
      Console.OutputEncoding = Encoding.GetEncoding("iso-8859-1");
      SCG.IEnumerable<String> ss;
      if (args.Length == 2)
        ss = ReadFileWords(args[0], int.Parse(args[1]));
      else
        ss = args;
      // foreach (String s in FirstAnagramOnly(ss)) 
      //   Console.WriteLine(s);
      //   Console.WriteLine("===");
      Timer t = new Timer();
      SCG.IEnumerable<SCG.IEnumerable<String>> classes = AnagramClasses(ss);
      int count = 0;
      foreach (SCG.IEnumerable<String> anagramClass in classes)
      {
        count++;
        // foreach (String s in anagramClass) 
        //   Console.Write(s + " ");
        // Console.WriteLine();
      }
      Console.WriteLine("{0} non-trivial anagram classes", count);
      Console.WriteLine(t.Check());
    }

    // Read words at most n words from a file

    public static SCG.IEnumerable<String> ReadFileWords(String filename, int n)
    {
      Regex delim = new Regex("[^a-zæøåA-ZÆØÅ0-9-]+");
      Encoding enc = Encoding.GetEncoding("iso-8859-1");
      using (TextReader rd = new StreamReader(filename, enc))
      {
        for (String line = rd.ReadLine(); line != null; line = rd.ReadLine())
        {
          foreach (String s in delim.Split(line))
            if (s != "")
              yield return s.ToLower();
          if (--n == 0)
            yield break;
        }
      }
    }

    // From an anagram point of view, a word is just a bag of
    // characters.  So an anagram class is represented as TreeBag<char>
    // which permits fast equality comparison -- we shall use them as
    // elements of hash sets or keys in hash maps.

    public static TreeBag<char> AnagramClass(String s)
    {
      TreeBag<char> anagram = new TreeBag<char>(Comparer<char>.Default, EqualityComparer<char>.Default);
      foreach (char c in s)
        anagram.Add(c);
      return anagram;
    }

    // Given a sequence of strings, return only the first member of each
    // anagram class.

    public static SCG.IEnumerable<String> FirstAnagramOnly(SCG.IEnumerable<String> ss)
    {
      SCG.IEqualityComparer<TreeBag<char>> tbh
        = UnsequencedCollectionEqualityComparer<TreeBag<char>, char>.Default;
      HashSet<TreeBag<char>> anagrams = new HashSet<TreeBag<char>>(tbh);
      foreach (String s in ss)
      {
        TreeBag<char> anagram = AnagramClass(s);
        if (!anagrams.Contains(anagram))
        {
          anagrams.Add(anagram);
          yield return s;
        }
      }
    }

    // Given a sequence of strings, return all non-trivial anagram
    // classes.  Should use a *sequenced* equalityComparer on a TreeBag<char>,
    // obviously: after all, characters can be sorted by ASCII code.  On
    // 347 000 distinct Danish words this takes 70 cpu seconds, 180 MB
    // memory, and 263 wall-clock seconds (due to swapping).

    // Using a TreeBag<char> and a sequenced equalityComparer takes 82 cpu seconds
    // and 180 MB RAM to find the 26,058 anagram classes among 347,000
    // distinct words.

    // Using an unsequenced equalityComparer on TreeBag<char> or HashBag<char>
    // makes it criminally slow: at least 1200 cpu seconds.  This must
    // be because many bags get the same hash code, so that there are
    // many collisions.  But exactly how the unsequenced equalityComparer works is
    // not clear ... or is it because unsequenced equality is slow?

    public static SCG.IEnumerable<SCG.IEnumerable<String>> AnagramClasses(SCG.IEnumerable<String> ss)
    {
      bool unseq = true;
      IDictionary<TreeBag<char>, TreeSet<String>> classes;
      if (unseq)
      {
        SCG.IEqualityComparer<TreeBag<char>> unsequencedTreeBagEqualityComparer
    = UnsequencedCollectionEqualityComparer<TreeBag<char>, char>.Default;
        classes = new HashDictionary<TreeBag<char>, TreeSet<String>>(unsequencedTreeBagEqualityComparer);
      }
      else
      {
        SCG.IEqualityComparer<TreeBag<char>> sequencedTreeBagEqualityComparer
    = SequencedCollectionEqualityComparer<TreeBag<char>, char>.Default;
        classes = new HashDictionary<TreeBag<char>, TreeSet<String>>(sequencedTreeBagEqualityComparer);
      }
      foreach (String s in ss)
      {
        TreeBag<char> anagram = AnagramClass(s);
        TreeSet<String> anagramClass;
        if (!classes.Find(anagram, out anagramClass))
          classes[anagram] = anagramClass = new TreeSet<String>();
        anagramClass.Add(s);
      }
      foreach (TreeSet<String> anagramClass in classes.Values)
        if (anagramClass.Count > 1)
          yield return anagramClass;
    }
  }

// Crude timing utility ----------------------------------------

  public class Timer
  {
    private DateTime start;

    public Timer()
    {
      start = DateTime.Now;
    }

    public double Check()
    {
      TimeSpan dur = DateTime.Now - start;
      return dur.TotalSeconds;
    }
  }
}