C#暴力生成字符串全排列程序无输出问题求助
修复你的暴力枚举全排列C#代码
你的代码有几个关键问题导致没有输出甚至卡死,下面逐个修正:
问题点与修复说明
- Random不能在循环内重复实例化:短时间内多次
new Random()会因为系统时钟种子重复,生成完全一样的随机序列,根本没法生成新排列。把Random的实例化移到循环外面。 - 随机索引范围错了:
rnd.Next(anagram.Length - 1)会漏掉最后一个字符的索引(索引最大值是anagram.Length-1),改成rnd.Next(anagram.Length)才能覆盖所有索引。 - storeInt每次循环后必须清空:每次生成完一个排列后,要把storeInt里的索引清空,不然下次循环时所有索引都被标记为已使用,temp永远凑不够长度。
- 控制台输出格式错误:原代码的
Console.WriteLine(temp, storeStr.Count)不会显示计数,用字符串插值或者格式化参数才能正确输出内容和序号。
修正后的完整代码
using System; using System.Collections.Generic; namespace anagramSolver { class Program { static void Main(string[] args) { Console.WriteLine("Enter anagram:"); string anagram = Console.ReadLine(); string temp = ""; List<string> storeStr = new List<string>(); List<int> storeInt = new List<int>(); // 计算全排列总数(阶乘) int factorial = 1; for (int i = anagram.Length; i > 0; i--) { factorial *= i; } // 把Random实例化移到循环外 Random rnd = new Random(); while (storeStr.Count != factorial) { // 每次生成新排列前清空索引记录 storeInt.Clear(); temp = ""; while(temp.Length != anagram.Length) { // 修正随机索引范围,包含最后一个字符 int num = rnd.Next(anagram.Length); if (!storeInt.Contains(num)) { storeInt.Add(num); temp += anagram[num]; } } if (!storeStr.Contains(temp)) { storeStr.Add(temp); // 正确输出排列和当前计数 Console.WriteLine($"{temp} (第{storeStr.Count}个排列)"); } // 如果是重复的排列,什么也不用做,循环会自动重试 } } } }
额外说明
- 原代码里
List<string>(0)和List<int>(0)没必要指定初始容量,默认构造函数就够用。 - 重复排列的判断逻辑保留了你原来的暴力方式,虽然效率低,但符合你想要加深理解的需求。
内容的提问来源于stack exchange,提问作者Ramunerl
相关产品推荐
相关产品推荐

