1:- cba
2:- dsef
3:- sandy
Output :-
1:- abc
2:- defs
3:- adnsy
This is called alphabetized sorting using Anagram method.
To Use Anagram Method :-
Dictionary
If we use generic list in dictionary then it will take longer time to compute
Dictionary
Namespace :-
using System;
using System.Collections.Generic;
using System.IO;
Public class Anagrams
{
public static void Main()
{
Read and sort dictionary
var data = ReadText();
Read in user input and show anagrams
string lineToRead;
while ((lineToRead = Console.ReadLine()) != null)
{
ShowOutput(data, lineToRead);
}
}
Public Dictionary
{
var data = new Dictionary
Read each line
using (StreamReader readWholeText = new StreamReader("Some File .Text"))
{
string line;
while ((line = readWholeText.ReadLine()) != null)
{
Alphabetize the line for the key,Then add to the string
string alphabetize = Alphabetize(line);
string tempString = string.Empty;
if (data.TryGetValue(alphabetize, out tempString))
{
data[alphabetize] = tempString + "," + line;
}
else
{
data.Add(alphabetize, line);
}
}
}
return data;
}
Convert the text and sort it according to alphabet.
Public string Alphabetize(string text)
{
// Convert to char array, then sort and return
char[] arrayOfLine = text.ToCharArray();
Array.Sort(arrayOfLine);
return new string(arrayOfLine);
}
This method will show the output.
Public void ShowOutput(Dictionary
{
// Write value for alphabetized word
string tempText;
if (objDictionary.TryGetValue(Alphabetize(temp), out tempText))
{
Console.WriteLine(tempText);
}
else
{
Console.WriteLine("-");
}
}
}
0 comments:
Post a Comment