我搜索了stackoverflow和網絡的類似問題,但我找不到我需要的解決方案。動態嵌套循環生成C#中數組元素的所有可能的組合#
我在編寫代碼列表生成器。
所以例如我有一個字符列表像List<char> { 'a', 'b', 'c' };
。
和我有幾個設置,如(int)minLength
的2
和(int)maxLength
的3
。
,我想這樣的輸出:
aa
ab
ac
ba
bb
bc
ca
cb
cc
aaa
aab
aac
aba
abb
abc
aca
acb
acc
baa
bab
bac
bba
bbb
bbc
bca
bcb
bcc
caa
cab
cac
cba
cbb
cbc
cca
ccb
ccc
在gereral我只想kreate多維循環
,但我有做動態,因爲diferent的minLength,最大長度& charList值這一點。
,所以我用「自調用函數」走出這樣的例子:
private void loop() {
for(int i = 0; i < num; i++) {
// stuff
loop();
}
}
到目前爲止,我已經取得了以下一串代碼,但在這個階段,我被卡住...:
Thread mainThread;
List<char> azlower;
List<char> azupper;
List<char> nullnine;
List<char> totalChars;
int totalNum;
int levelCounter;
bool running;
public Form1() {
InitializeComponent();
}
private void init() {
azlower = new List<char> { 'a', 'b', 'c' , 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
azupper = new List<char> { 'A', 'B', 'C' , 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
nullnine = new List<char> { '0', '1', '2' /* , '3', '4', '5', '6', '7', '8', '9' */ };
totalChars = new List<char>();
running = false;
}
private void button1_Click(object sender, EventArgs e) {
if(!running) {
init();
// Start
if(checkBoxAZ1.Checked) {
foreach(char character in azlower) {
totalChars.Add(character);
}
}
if(checkBoxAZ2.Checked) {
foreach(char character in azupper) {
totalChars.Add(character);
}
}
if(checkBox09.Checked) {
foreach(char character in nullnine) {
totalChars.Add(character);
}
}
if(checkBoxS.Checked && textBoxSpec.Text != "") {
char[] specArray = textBoxSpec.Text.ToCharArray();
foreach(char character in specArray) {
totalChars.Add(character);
}
}
totalNum = totalChars.Count;
levelCounter = Int32.Parse(textBoxMinLength.Text);
mainThread = new Thread(new ThreadStart(run));
button1.Text = "Stop";
running = true;
mainThread.Start();
} else {
mainThread.Abort();
button1.Text = "Start";
running = false;
}
}
private void run() {
for(int i = 0; i < totalNum; i++) {
Invoke((MethodInvoker) delegate {
write(totalChars[ i ].ToString());
if(i == totalNum - 1 && levelCounter == Int32.Parse(textBoxMaxLength.Text)) {
write("\n");
}
});
if(levelCounter < Int32.Parse(textBoxMaxLength.Text)) {
levelCounter++;
run();
}
}
return;
}
private void write(string line) {
richTextBox1.Text += line;
}
,但上面的設置,我的代碼,輸出看起來是這樣的:
aabc
bc
我想我只是馬一個想法的錯誤,不是嗎?
so guys,you have anny suggestions for me?
我也看了看笛卡爾產品,但我認爲它不會只用一個陣列工作...
THX的任何幫助。
可能重複http://stackoverflow.com/questions/5162254/all-可能的組合數組) – 2013-03-26 15:22:15
@ReedCopsey雖然這個問題被標記爲C#所有的答案都是基於java的 – 2013-03-26 15:24:48
@ScottChamberlain有[噸的重複](http://stackoverflow.com/search?q=combi國家+陣列+ C%23)這已經 - 例如我發佈的一個,但也http://stackoverflow.com/questions/7643885/different-combinations-of-an-array-c和http:// stackoverflow .com/questions/5777208/array-of-array-combinations在這個網站上搜索將很容易引起大量的愚弄 – 2013-03-26 15:27:31