Skip to content

Instantly share code, notes, and snippets.

@efarioli
Created February 6, 2020 19:50
Show Gist options
  • Save efarioli/04737a896ee012ba1fd814ae345f9220 to your computer and use it in GitHub Desktop.
Save efarioli/04737a896ee012ba1fd814ae345f9220 to your computer and use it in GitHub Desktop.
Find all Anagrams. Given a very long list of words: find all the sets of anagrams, print each set, print the total quantity of sets and print the total quantity of words.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace task01
{
class Program
{
static void Main(string[] args)
{
Stopwatch st = new Stopwatch();
st.Start();
String[] wordarray = File.ReadAllLines("wordlist.txt");
Dictionary<string, List<string>> setOfanagrams = getSetOfAnagrams(wordarray);
PrintDictionary(setOfanagrams);
st.Stop();
Console.WriteLine(st.Elapsed);
Console.WriteLine("Program terminated");
Console.ReadKey();
}
public static Dictionary<string, List<string>> getSetOfAnagrams (string [] wordsArray)
{
Dictionary<string, List<string>> dic = new Dictionary<string, List<string>>();
Dictionary<string, List<string>> dic2 = new Dictionary<string, List<string>>();
int size = wordsArray.Length;
string el;
string el_ord;
for (int i = 0; i < size; ++i)
{
el = wordsArray[i];
el_ord = String.Concat(el.OrderBy(c => c));// potato -> aooptt // waisters -> aeirsstw // waitress -> aeirsstw // wastries -> aeirsstw
if (!dic.ContainsKey(el_ord))
{
dic.Add(el_ord, new List<string>());
}
dic[el_ord].Add(el);
}
foreach (KeyValuePair<string, List<string>> entry in dic)
{
if (entry.Value.Count > 1)
{
dic2.Add(entry.Key, entry.Value);
}
}
return dic2;
}
public static void PrintDictionary (Dictionary<string, List<string>> dictionary)
{
int qtySetAnagrams = 0;
int qtyTotalOfWords = 0;
foreach (KeyValuePair<string, List<string>> entry in dictionary)
{
Console.Write(++qtySetAnagrams + " : (" + string.Join(", ", entry.Value) + ")-----");
qtyTotalOfWords += entry.Value.Count;
}
Console.WriteLine("\n\n\tTotal sets of anagrams: " + qtySetAnagrams);
Console.WriteLine("\tTotal quantity of words: " + qtyTotalOfWords);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment