c# - 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 的组合。
我尝试了什么:我创建了代码,该代码使用随机数从字符串数组生成结果,以从字符串数组中随机选择一个索引,并最终在理论上通过随机选择生成所有可能的组合,但这真的很慢在生成相同的值时可能会很糟糕。
字符串数组、排列和上下文的具体要求使得这很难在网上找到可以用来提供帮助的帮助。感谢您对这项复杂任务的任何帮助!
解决方案
推荐阅读
- java - 在 BottomDialogFragment 我有使 Draggble 为假但它收到警告消息
- cassandra - Cassandra JVM 约束
- android - sdk 22 和 25 之间的 ACCESS_FINE_LOCATION 和 ACCESS_COARSE_LOCATION 权限有什么区别吗?
- javascript - Is it a good idea to use the "setState" function in JavaScript even if the previous state is irrelevant?
- python - seaborn swarmplot 中的水平图
- css - css INLINE-BLOCK div 居中对齐但保持内部元素仍左对齐
- node.js - 异步/等待错误返回 Promise {
} - powershell - 如何在 PowerShell 中返回自定义错误级别?
- mysql - 如何删除 SQL 中的重复(两行混合)行?
- node.js - 基于 swagger 文件验证请求的独立 NPM 库