c# - C#中来自2个不同字符串的所有可能的字符组合
问题描述
谁能帮我解决这个问题?
它应该是一个要求输入名字和姓氏的 ConsoleApp。从所有名称中,它应该生成 4 个字符。我必须提供字符串的不同可能组合(例如 1. 和 3. char 的 fn 和 2. 3. char 的 ln ...) 算法应该能够提供 4 个字符的所有可能组合,其中 2 来自名字和 2 个姓氏。
到目前为止,我只为名字和姓氏做了 2 的组合。
static void Main(string[] args)
{
Console.WriteLine("Enter your first name");
string firstName = Console.ReadLine();
Console.WriteLine("Enter your last name");
string lastName = Console.ReadLine();
string[] result = GetAllCombinations(firstName);
string[] code = GetAllCombinations(lastName);
PrintTheCombinations(result);
PrintTheCombinations(code);
}
private static void PrintTheCombinations(string[] list)
{
foreach (var results in list)
{
Console.WriteLine(results);
}
}
private static string[] GetAllCombinations(string word)
{
int arraylength = word.Length * word.Length;
var ret = new string[arraylength];
for (int i = 0; i < word.Length; i++)
{
for (int j = 0; j < word.Length; j++)
{
ret[i * word.Length + j] = string.Concat(word[i], word[j]);
}
}
return ret;
}
现在我需要打印 4 个字符,2 个 fn 和 2 个 ln,但我被卡住了。希望你们明白我的意思
解决方案
可以这样做
static void Main(string[] args)
{
//Console.WriteLine("Enter your first name");
//string firstName = Console.ReadLine().ToUpper();
//Console.WriteLine("Enter your last name");
//string lastName = Console.ReadLine().ToUpper();
string firstName = "abc".ToUpper();
string lastName = "123".ToUpper();
var first = new HashSet<string>();
var second = new HashSet<string>();
foreach (var permutation in Permutations(firstName))
{
var value = $"{permutation[0]}{permutation[1]}";
if (!first.Contains(value))
{
first.Add(value);
}
}
foreach (var permutation in Permutations(lastName))
{
var value = $"{permutation[0]}{permutation[1]}";
if (!second.Contains(value))
{
second.Add(value);
}
}
var result = new HashSet<string>();
foreach (var begin in first)
{
foreach (var end in second)
{
var value = $"{begin}{end}";
if (!result.Contains(value))
{
result.Add(value);
Console.WriteLine(value);
}
}
}
}
static IEnumerable<string> Permutations(string word)
{
if (word == null || word.Length <= 1)
{
yield return word;
yield break;
}
char firstChar = word[0];
foreach (string subPermute in Permutations(word.Substring(1)))
{
int indexOfFirstChar = subPermute.IndexOf(firstChar);
if (indexOfFirstChar == -1) indexOfFirstChar = subPermute.Length;
for (int index = 0; index <= indexOfFirstChar; index++)
yield return subPermute.Insert(index, new string(firstChar, 1));
}
}
推荐阅读
- angular - 如何使用 contentChild 在组件中获取 ng-template 和 ngModel
- azure - Azure cosmos db地理数据查询不一致
- sql - 如果其中一个 ID 包含特定单词,则从结果中删除所有重复的 ID
- flutter - 高度小于 50 时 Flutter TextFIeld 不居中
- postgresql - POSTGRES:在 ALTER 查询中使用选择的结果
- c# - 本地无法启动topshelf服务:服务没有及时响应
- sql-server - 全文搜索不适用于前缀“the”
- ios - 了解 RxSwift 中的保留周期
- android - Flutter:意外地在 360x780 上创建了我的整个 UI。如何使其在其他手机屏幕上均匀调整大小?
- python-3.x - dnspython:在 pycharm 中找不到模块