Reputation: 61
I am trying to create a program that will give me every single digit between 1 and 55 but 6 times in a row.
That is;
1-17-25-45-49-51
55-54-53-52-51-50
Note, two numbers can never repeat in a row.
I've tested this program on a smaller scale and so far it does as intended. However, if I run it full scale, as the code posted bellow shows, it runs into an "out of memory exception". My guess is, its because of the memory having to hold such big numbers while building the ArrayList and file consecutively.
How do I go about fixing this?
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 ();
}
}
}
Upvotes: 0
Views: 834
Reputation: 36483
Without trying to fix the rest of your code, the basic principle you need to follow is to write out the numbers as you get them, instead of cumulating them in a list. You can get rid of the ArrayList
altogether, and the accompanying foreach
loop.
The relevant part would look like this:
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++;
}
}
}
}
}
}
}
But, be warned. Your code will take a long time to complete. You just won't get the out of memory error. You may run out of hard disk space though :)
Upvotes: 2