快速的问题。 我写一个程序,找出一组字符I输入到应用程序的所有排列。 这部分作品完美。 我的问题是,我需要检查字符的所有排列反对我的字典使用的文本文件。 防爆。 如果我输入字符TSTE得到安宁的输出是不同厂家,TTSE,TTES,毒鼠强,测试,上海技术交易所,STET,SETT ......我只想打印有效的话像TSET,SETT,STET,测试,毒鼠强。 其中TTSE,TTES,STTE不打印。
我到目前为止的代码如下。 我在我的头骨,在过去几天的边缘被scracthing,只是不能似乎找到一个方法来做到这一点。 如果有,请什么你可以看到,我错过了什么?
谢谢
static void Main(string[] args)
{
Console.BufferHeight = Int16.MaxValue - 1;
Console.WindowHeight = 40;
Console.WindowWidth = 120;
Permute p = new Permute();
var d = Read();
string line;
string str = System.IO.File.ReadAllText("Dictionary.txt");
while ((line = Console.ReadLine()) != null)
{
char[] c2 = line.ToArray();
p.setper(c2);
}
}
static Dictionary<string, string> Read()
{
var d = new Dictionary<string, string>();
using (StreamReader sr = new StreamReader("Dictionary.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string a = Alphabet(line);
string v;
if (d.TryGetValue(a, out v))
{
d[a] = v + "," + line;
}
else
{
d.Add(a, line);
}
}
}
return d;
}
static string Alphabet(string s)
{
char[] a = s.ToCharArray();
Array.Sort(a);
return new string(a);
}
static void Show(Dictionary<string, string> d, string w)
{
string v;
if (d.TryGetValue(Alphabet(w), out v))
{
Console.WriteLine(v);
}
else
{
Console.WriteLine("-----------");
}
}
}
class Permute
{
private void swap(ref char a, ref char b)
{
if (a == b) return;
a ^= b;
b ^= a;
a ^= b;
}
public void setper(char[] list)
{
int x = list.Length - 1;
go(list, 0, x);
}
public void go(char[] list1, int k, int m)
{
if (k == m)
{
Console.WriteLine(list1);
Console.WriteLine(" ");
}
else
{
for (int i = k; i <= m; i++)
{
swap(ref list1[k], ref list1[i]);
go(list1, k + 1, m);
swap(ref list1[k], ref list1[i]);
}
}
}
你只是错过展(d,线); i循环。
改变这样的。
while ((line = Console.ReadLine()) != null)
{
char[] c2 = line.ToArray();
p.setper(c2);
Console.WriteLine(" combinations which are in Dictionary are:");
Show(d, line);
}
那么...你没有必要的词典
use List<string> Dic=new List<string>();// declare it in globally
Dic.add(line); //each line in dictionary
打印每个字之前
if(Dic.contains(word))
print it;
else{ //no printing }
不可能的当前状态。
这是可能的,因为
如果“dictionary.txt”是你的输入,那么你没有定义什么是有效的话 。 您在leaset需要另一个字典定义这些有效的单词或算法来决定那些是什么,那些是不算什么。
如果输入的是用户界面和“dictionary.txt”是定义有效的话 ,你并不需要该置换的输入,只需搜索从“dictionary.txt”的输入。
然而,你的Read
方法改善的,如
static Dictionary<String, String> Read(String path) {
return (
from line in File.ReadAllLines(path)
where false==String.IsNullOrEmpty(line)
group line by Alphabet(line) into g
select
new {
Value=String.Join(",", g.ToArray()),
Key=g.Key
}
).ToDictionary(x => x.Key, x => x.Value);
}
虽然有效的话是因为我在另一个答复中提到,无法与你目前的状态,我就使代码对你很清楚。
最后,它的代码,由三个部分分离。 它们是Permutable<T>
ConsoleHelper
和ConsoleApplication1.Program
与效用Permutation
类。
置换<T>(Permutable.cs)
using System.Collections.Generic; using System.Collections; using System; public partial class Permutable<T>: IEnumerable { public static explicit operator Permutable<T>(T[] array) { return new Permutable<T>(array); } static IEnumerable Permute<TElement>(IList<TElement> list, int depth, int count) { if(count==depth) yield return list; else { for(var i=depth; i<=count; ++i) { Swap(list, depth, i); foreach(var sequence in Permutable<T>.Permute(list, 1+depth, count)) yield return sequence; Swap(list, depth, i); } } } static void Swap<TElement>(IList<TElement> list, int depth, int index) { var local=list[depth]; list[depth]=list[index]; list[index]=local; } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } public IEnumerator<IList<T>> GetEnumerator() { var list=this.m_List; if(list.Count>0) foreach(IList<T> sequence in Permutable<T>.Permute(list, 0, list.Count-1)) yield return sequence; } protected Permutable(IList<T> list) { this.m_List=list; } IList<T> m_List; }
ConsoleHelper(ConsoleHelper.cs)
using System.Runtime.InteropServices; using System.Windows.Forms; using System.Drawing; using System; using System.Collections.Generic; using System.Linq; using System.Text; public static partial class ConsoleHelper { [StructLayout(LayoutKind.Sequential)] public struct RECT { public static explicit operator Rectangle(RECT rect) { return new Rectangle { X=rect.Left, Y=rect.Top, Width=rect.Right-rect.Left, Height=rect.Bottom-rect.Top }; } public int Left; public int Top; public int Right; public int Bottom; } [DllImport("user32.dll", SetLastError=true)] static extern bool MoveWindow(IntPtr hWnd, int X, int Y, int Width, int Height, bool repaint); [DllImport("user32.dll", SetLastError=true)] static extern bool GetWindowRect(IntPtr hWnd, out RECT rect); [DllImport("kernel32.dll", SetLastError=true)] static extern IntPtr GetConsoleWindow(); public static void CenterScreen() { RECT rect; var hWnn=ConsoleHelper.GetConsoleWindow(); var workingArea=Screen.GetWorkingArea(Point.Empty); ConsoleHelper.GetWindowRect(hWnn, out rect); var rectangle=(Rectangle)rect; rectangle= new Rectangle { X=(workingArea.Width-rectangle.Width)/2, Y=(workingArea.Height-rectangle.Height)/2, Width=rectangle.Width, Height=rectangle.Height }; ConsoleHelper.MoveWindow( hWnn, rectangle.Left, rectangle.Top, rectangle.Width, rectangle.Height, true ); } }
ConsoleApplication1.Program&组合(Program.cs中)
using System.Collections; using System.IO; using System; using System.Collections.Generic; using System.Linq; using System.Text; public partial class Permutation { public static Permutation FromFile(String path) { return new Permutation(path); } public static String GetSortedAlphabet(String text) { var array=text.ToArray(); Array.Sort(array); return new String(array); } public Dictionary<String, String> Dictionary { private set; get; } public FileInfo SourceFile { private set; get; } public Permutation(String path) { this.Dictionary=( from line in File.ReadAllLines(path) where false==String.IsNullOrEmpty(line) group line by Permutation.GetSortedAlphabet(line) into g select new { Value=String.Join(", ", g.Distinct().ToArray()), Key=g.Key } ).ToDictionary(x => x.Key, x => x.Value); this.SourceFile=new FileInfo(path); } } namespace ConsoleApplication1 { partial class Program { static void ProcessLine(IList<char> input) { Console.WriteLine(); if(input.Count>0) { var inputArray=input.ToArray(); var key=Permutation.GetSortedAlphabet(new String(inputArray)); var dict=Program.Permutation.Dictionary; var hasKey=dict.ContainsKey(key); var source=Permutation.SourceFile; Console.WriteLine("Possible permutations are: "); foreach(var sequence in (Permutable<char>)inputArray) Console.WriteLine("{0}", new String(sequence.ToArray())); Console.WriteLine("Acceptable in file '{0}' are: ", source.FullName); Console.WriteLine("{0}", hasKey?dict[key]:"<none>"); Console.WriteLine(); input.Clear(); } Console.Write(Prompt); } static void ProcessChar(IList<char> input, char keyChar) { Console.Write(keyChar); input.Add(keyChar); } static void ProcessExit(IList<char> input, char keyChar) { Console.WriteLine(); Console.Write("Are you sure to exit? (Press Esc again to exit)"); input.Add(keyChar); } static bool ProcessLast(IList<char> input, char keyChar) { var last=input.Count-1; if(0>last||input[last]!=(char)ConsoleKey.Escape) return false; input.Clear(); return true; } public static Permutation Permutation { private set; get; } public static String Prompt { private set; get; } } partial class Program { static void Main(String[] args) { Console.BufferHeight=short.MaxValue-1; Console.SetWindowSize(120, 40); ConsoleHelper.CenterScreen(); var input=new List<char>(char.MaxValue); Program.Permutation=Permutation.FromFile(@"c:\dictionary.txt"); Program.Prompt="User>\x20"; Program.ProcessLine(input); for(; ; ) { var keyInfo=Console.ReadKey(true); var keyChar=keyInfo.KeyChar; var keyCode=keyInfo.Key; if(ConsoleKey.Escape==keyCode) { if(Program.ProcessLast(input, keyChar)) break; Program.ProcessExit(input, keyChar); continue; } if(ConsoleKey.Enter==keyCode) { Program.ProcessLine(input); continue; } if(default(ConsoleModifiers)!=keyInfo.Modifiers) continue; if(0x1f>keyChar||keyChar>0x7f) continue; if(Program.ProcessLast(input, keyChar)) Console.WriteLine(); Program.ProcessChar(input, keyChar); } } } }
该ConsoleHelper
类只使用ceteral您调整大小的控制台窗口,你可以测试程序更加舒适。 该Permutable
类是什么我完全从你的原班重新设计; 现在配备IEnumerable
来排列,也是一个泛型类。
的Permutation
类,就像是一个工具类,本身提供一个FromFile
方法作为原始Read
,并存储该Dictionary<String, String>
作为属性。 最初的方法Alphabet
被重命名GetSortedAlphabet
更多的语义。
该Program
类主要有四个静态ProcessXXX
方法,它们是
- ProcessChar:处理用于
char
的范围内的从0x20
到0x7f
- ProcessLine从:流程,
Enter
压 - ProcessExit:为进程
Excape
压 - ProcessLast:额外的处理
ProcessLine
和ProcessExit
是的,我的意思是让他们有名字的长度相同。 如需更多信息, Program
类有两个静态属性; Permutation
用于存储类的实例Permutation
,并Prompt
是提示用户的字符串。
当您输入未在规定"c:\dictionary.txt"
中,提示"Acceptable in file .."
将让你"<none>"
。
exit命令两次逃生按键,你会看到
你确定要退出吗? (可退出按Esc键)
如果按Enter
或其它键,它恢复到初始状态。
就这样。 现在是时候来发现你遭遇的最后问题。 在您用这个程序测试,你可能会更清楚地说明你的问题和问题。
祝好运!
感谢您对所有您的反馈意见。 我终于想通了,并找到了解决我遇到的问题。 静态无效的主要(字符串[]参数){Console.BufferHeight = Int16.MaxValue - 1;
Console.WindowHeight = 40;
Console.WindowWidth = 120;
Console.WriteLine("Enter your caracters for the anagram: ");
//var d = Read();
string line;
//string DictionaryInput = System.IO.File.ReadAllText("Dictionary.txt");
while ((line = Console.ReadLine()) != null)
{
Console.WriteLine("Your results are: ");
char[] charArray = line.ToArray();
//Show(d, line); //Using this to check that words found are the correct words in the dictionary.
setper(charArray);
Console.WriteLine("-----------------------------------------DONE-----------------------------------------");
Console.WriteLine("Enter your caracters for the anagram: ");
File.Delete("Permutations.txt");
}
}
static void swap(ref char a, ref char b)
{
if (a == b) return;
a ^= b;
b ^= a;
a ^= b;
}
static void setper(char[] list)
{
int x = list.Length - 1;
permuteWords(list, 0, x);
}
static void permuteWords(char[] list1, int k, int m)
{
if (k == m)
{
StreamWriter sw = new StreamWriter("Permutations.txt", true);
sw.WriteLine(list1);
sw.Close();
Regex permutationPattern = new Regex(new string(list1));
string[] permutations = File.ReadAllLines("Permutations.txt");
Regex pattern = new Regex(new string(list1));
string[] lines = File.ReadAllLines("Dictionary.txt");
foreach (string line in lines)
{
var matches = pattern.Matches(line);
if (pattern.ToString() == line)
{
Console.WriteLine(line);
}
}
}
else
{
for (int i = k; i <= m; i++)
{
swap(ref list1[k], ref list1[i]);
permuteWords(list1, k + 1, m);
swap(ref list1[k], ref list1[i]);
}
}
}