首页 > 解决方案 > C# 为字符串数组生成长度为 n 的所有组合和排列

问题描述

这是我长期以来一直面临的一个问题,我在互联网上搜索了很多人向自己提出类似问题,但从未真正适用于我的情况。我的任务的目标是使用字符串数组并生成一定长度的所有排列和组合。例如(手写,因此可能不是 100% 准确)

string[] values = new string[] { "ye", "ok", "nice", "5");
int length = 3;
:
yeoknice
yeok5
yeniceok
yenice5
ye5ok
ye5nice
okyenice
okye5
okniceye
oknice5
ok5nice
ok5ye
niceokye
niceok5
niceyeok
niceye5
nice5ok
nice5ye
5niceok
5niceye
5okye
5oknice
5yeok
5yenice

还可以在字符串数组中添加更多值,例如字符串数组中的 100+ 个值,并且长度也设置为 100 左右。

我写了一些伪代码:

string generatedvalue;
int64 progress = 0;//so that if the generating takes along time the code can read from file and see the progress and start generating where it left off. i think if the amount of numbers its generating is big then the progress value could be big too maybe it would be good to support something higher like int512
string[] values = new string[] { "ye", "ok", "nice", "5", "ohyeah", "rate", "best", "a", "b", "c", "f");
int length = 7;

//generate all combinations and perumtations
loop(conditions{
progress++;

//magic
? :(
//
generatedvalue = resultsfrommagic // put one of the combinations into the generatedvalue and write it to file so all the combinations and permutations are stored in a file on a new line

//write to file
writetofileappendnewline(progress + generatedvalue)
}
}

结果来自我的在线研究:我找到了一个非常接近的页面,如果不是问题的答案(除了我不知道它是否有效并且它不接受字符串数组只接受数字)但它不在 c# 中并且语法很奇怪所以我不能开始翻译它或开始将它包含在我的工作中(因为我不懂那种语言,所以它可能不是问题的真正答案)https://elixirforum.com/t/generate-all-具有固定阵列大小/26196 的组合

我尝试了什么:我创建了代码,该代码使用随机数从字符串数组生成结果,以从字符串数组中随机选择一个索引,并最终在理论上通过随机选择生成所有可能的组合,但这真的很慢在生成相同的值时可能会很糟糕。

字符串数组、排列和上下文的具体要求使得这很难在网上找到可以用来提供帮助的帮助。感谢您对这项复杂任务的任何帮助!

标签: c#.netpermutation

解决方案


推荐阅读