I am building a program in which the user types in a desired word and the word is placed into an ArrayList letter by letter. A random letter generator then begins and then every one of the generated letters is placed into another ArrayList. The letters in both lists are then compared and the program stops once the generator randomly spells the desired word.
An execution for a high probability looks like this:
Would you like to use:
1. Lowercase Letters
2. Uppercase Letters
3. Numbers
4. Special Characters
5. Space
(Example, if you'd like to use Lowercase Letters and Numbers, type "13")
1
What character(s) would you like to be tested?
(Example: "RaNdOm123", "Stephen")
j
u
f
p
b
z
t
j
Successful! 7 characters generated until completion.
But when there is a really low probability, the program runs and eventually shows this exception:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Unknown Source)
at java.util.Arrays.copyOf(Unknown Source)
at java.util.ArrayList.grow(Unknown Source)
at java.util.ArrayList.ensureExplicitCapacity(Unknown Source)
at java.util.ArrayList.ensureCapacityInternal(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
at Generator.stringGenerator(Generator.java:53)
at Driver.main(Driver.java:16)
This is the code that creates and compares the ArrayLists:
for (int i = 0; i < desiredText.length(); i++) {
desiredArray.add(desiredText.charAt(i));
}
boolean proceed = true;
int k = 0;
int l = 0;
do {
Random r = new Random();
for (int i = 0; i < desiredText.length(); i++) {
int n = r.nextInt(limit);
randomArray.add(line.charAt(n));
System.out.println(randomArray.get(k));
k++;
if (!desiredArray.get(i).equals(randomArray.get(l))) {
l++;
break;
} else {
l++;
}
if (i == desiredText.length() - 1) {
proceed = false;
System.out.println("Successful!");
System.out.println(randomArray.size() + " characters generated until completion.");
break;
}
}
} while (proceed == true);
I was thinking about checking to see if the size of the randomArray is larger than the length of the desiredText. If it is, then I'd remove the first element of the array and loop this entire process. Would doing that use less memory? If not, do you have any suggestions for how to modify the code so this exception isn't thrown for extensive ArrayList's? The largest ArrayList that has successfully made the desired word was about 65 million characters long. I'd like to get to the point where I could use an entire paragraph as the desired word and let the program run for days until it randomly types it. All help will be appreciated. Thanks.
long intinstead ofrandomArray.size()