我正在尝试创建一个程序,它将为我提供1到55之间但连续6次的每个数字。
那是;
1-17-25-45-49-51
55-54-53-52-51-50
注意,两个数字不能连续重复。
我已经对这个程序进行了较小规模的测试,到目前为止它已按预期进行。但是,如果我全面运行它,如下面显示的代码所示,它会遇到内存异常"。我的猜测是,因为内存必须在连续构建ArrayList和文件时保持如此大的数字。
我该如何解决这个问题?
class MainClass
{
public static void Main (string[] args)
{
ArrayList newWords= new ArrayList();
System.Console.WriteLine ("Please enter word to prepend ");
int wordCount = 0;
string numbers;
string word = Console.ReadLine ();
string word2 = word;
string separator = "-";
System.Console.WriteLine ("Please enter location of where you would like the new text file to be saved: ");
string newFileDestination = Console.ReadLine ();
TextWriter writeToNewFile = new StreamWriter (newFileDestination);
for(int a = 1; a < 56; a++){
for(int b = 1; b < 56; b++){
for(int c = 1; c < 56; c++){
for(int d = 1; d < 56; d++){
for(int e = 1; e < 56; e++){
for(int f = 1; f < 56; f++){
if(a != b && a != c && a != c && a != e && a != f && b != c && b != d && b != e && b != f && c != d && c != e && c != f && d != e && d != f && e != f){
word = word2;
numbers = string.Concat(a, separator, b, separator, c, separator, d, separator, e, separator, f);
word += numbers;
newWords.Add (word);
}
}
}
}
}
}
}
foreach(string line in newWords){
writeToNewFile.WriteLine(line);
Console.WriteLine (line);
wordCount++;
}
writeToNewFile.Close ();
Console.WriteLine (wordCount);
Console.WriteLine ("Press any key to exit.");
System.Console.ReadKey ();
}
}
}
答案 0 :(得分:2)
在不尝试修复其余代码的情况下,您需要遵循的基本原则是在获取数字时写出数字,而不是将它们累积在列表中。你可以完全摆脱ArrayList
和随附的foreach
循环。
相关部分如下所示:
TextWriter writeToNewFile = new StreamWriter (newFileDestination);
for(int a = 1; a < 56; a++){
for(int b = 1; b < 56; b++){
for(int c = 1; c < 56; c++){
for(int d = 1; d < 56; d++){
for(int e = 1; e < 56; e++){
for(int f = 1; f < 56; f++){
if(a != b && a != c && a != c && a != e && a != f && b != c && b != d && b != e && b != f && c != d && c != e && c != f && d != e && d != f && e != f){
word = word2;
numbers = string.Concat(a, separator, b, separator, c, separator, d, separator, e, separator, f);
word += numbers;
writeToNewFile.WriteLine(word);
Console.WriteLine (word);
wordCount++;
}
}
}
}
}
}
}
但是,请注意。您的代码需要很长时间才能完成。你只是不会得到内存不足的错误。您可能会耗尽硬盘空间:)