检查文本文件中是否包含字符的排列
本文关键字:字符 排列 包含 是否 文本 文件 检查 | 更新日期: 2023-09-27 18:02:21
快速提问。我正在编写一个程序来查找我输入到应用程序中的一组字符的所有排列。这部分工作得很好。我的问题是,我需要根据我用作字典的文本文件检查字符的所有排列。例如,如果我输入字符TSTE,给出的输出是tset,ttse,ttes,tets,test,stte,stet,set…我只想打印有效的单词,比如tset,set,stet,test,tets。其中不打印ttse,ttes,stte
到目前为止,我得到的代码如下:在过去的几天里,我一直在抓挠我的头骨边缘,似乎就是找不到一个方法来做。请问有什么是我遗漏的吗?谢谢
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]);
}
}
}
你错过了Show(d, line);我循环。
像这样改变
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"是你的输入,那么你没有定义什么是有效的单词。您至少需要另一个字典来定义那些有效的单词,或者需要一个算法来决定哪些是有效的,哪些不是。
-
如果输入来自UI并且"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
类。
-
Permutable
(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.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
类仅用于调整您的控制台窗口大小,以便您可以更舒适地测试程序。Permutable
课程是我从你原来的课程中完全重新设计的;它现在有IEnumerable
来排列,也是一个泛型类。
Permutation
类,就像一个实用程序类,它本身提供了一个FromFile
方法作为你原来的Read
,并存储Dictionary<String, String>
作为一个属性。原来的方法Alphabet
被重命名为GetSortedAlphabet
以获得更多的语义。
Program
类有四个主要的静态ProcessXXX
方法,它们是
- ProcessChar:
char
范围从0x20
到0x7f
的进程 - ProcessLine:
Enter
的进程按 - processsexit:
Excape
的进程按 - ProcessLast:
ProcessLine
和ProcessExit
的附加处理
是的,我的意思是使它们具有相同长度的名称。更多地,Program
类有两个静态属性;Permutation
用于存储类Permutation
的实例,Prompt
是一个字符串,用于提示用户。
当您的输入没有在"c:'dictionary.txt"
中定义时,"Acceptable in file .."
的提示符将显示"<none>"
。
退出命令是按两次escape键,你会看到
您确定要退出吗?(再次按Esc退出)
,如果您按下Enter
或其他键,它将返回到初始状态。
。现在是时候发现你遇到的最后一个问题了。在你用这个程序测试之后,你可能会更清楚地描述你的问题和问题。
祝你好运!
感谢您的反馈。我终于弄明白了,找到了解决我遇到的问题的方法。静态void Main(string[] args){控制台。BufferHeight = Int16。
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]);
}
}
}