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

AnagramStrings.cs « UserGuideExamples « Mono.C5 « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 314e7a41111402b064d6401a0a18e110fac3b310 (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
/*
 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 represented as sorted strings 2004-08-26

// To represent an anagram class, use a string containing the sorted
// characters of a word.  

// This is faster than a TreeBag<char> because the words and hence
// bags are small.  Takes 15 CPU seconds and 138 MB RAM to find the
// 26,058 anagram classes among 347,000 distinct words.

// 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 AnagramStrings
{
  class MyTest
  {
    public static void Main(String[] args)
    {
      Console.OutputEncoding = Encoding.GetEncoding("iso-8859-1");
      SCG.IEnumerable<String> ss;
      if (args.Length == 1)
        ss = ReadFileWords(args[0]);
      else
        ss = args;

      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} anagram classes", count);
      Console.WriteLine(t.Check());
    }

    // Read words from a file

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

    // From an anagram point of view, a word is just a bag of characters.

    public static CharBag AnagramClass(String s)
    {
      return new CharBag(s);
    }

    // Given a sequence of strings, return all non-trivial anagram classes   

    public static SCG.IEnumerable<SCG.IEnumerable<String>> AnagramClasses(SCG.IEnumerable<String> ss)
    {
      IDictionary<CharBag, HashSet<String>> classes
        = new TreeDictionary<CharBag, HashSet<String>>();
      foreach (String s in ss)
      {
        CharBag anagram = AnagramClass(s);
        HashSet<String> anagramClass;
        if (!classes.Find(anagram, out anagramClass))
          classes[anagram] = anagramClass = new HashSet<String>();
        anagramClass.Add(s);
      }
      foreach (HashSet<String> anagramClass in classes.Values)
        if (anagramClass.Count > 1
      ) // && anagramClass.Exists(delegate(String s) { return !s.EndsWith("s"); }))
          yield return anagramClass;
    }
  }

// A bag of characters is represented as a sorted string of the
// characters, with multiplicity.  Since natural language words are
// short, the bags are small, so this is vastly better than
// representing character bags using HashBag<char> or TreeBag<char>

  class CharBag : IComparable<CharBag>
  {
    private readonly String contents; // The bag's characters, sorted, with multiplicity

    public CharBag(String s)
    {
      char[] chars = s.ToCharArray();
      Array.Sort(chars);
      this.contents = new String(chars);
    }

    public override int GetHashCode()
    {
      return contents.GetHashCode();
    }

    public bool Equals(CharBag that)
    {
      return this.contents.Equals(that.contents);
    }

    public int CompareTo(CharBag that)
    {
      return this.contents.CompareTo(that.contents);
    }
  }

// 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;
    }
  }
}