I created a simple program to read from a list some values and keep only those of a specified length and also to extract 3 characters from them, but from a different position each time.
For example if we have the value nick07n the program should extract three random characters from it that might be the same but not taken from the same position:
n0n [0, 4, 6]
While the program runs correctly (as I've seen some results), the whole procedure is not performed successfully until the end or not performed at all, as I receive the following memory error:
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 guessingTool.CheckProgram.main(CheckProgram.java:103)
Here is the code I have so far:
for (int i = 0; i < 5; i++) {
index = randomGenerator.nextInt(valuesList.size());
value = valuesList.get(index);
finalValue = "";
positions.clear();
for (int j = 0; j < 3; j++) {
index = randomGenerator.nextInt(value.length());
valueChar = value.charAt(index);
positions.add(index);
if (j == 0) {
finalValue += Character.toString(valueChar);
}
else if (j == 1) {
if (positions.get(0) != positions.get(1)) {
finalValue += Character.toString(valueChar);
}
else {
while (positions.get(0) == positions.get(1)) {
index = randomGenerator.nextInt(value.length());
valueChar = value.charAt(index);
positions.add(index);
}
}
}
else if (j == 2) {
if (positions.get(0) != positions.get(2) && positions.get(1) != positions.get(2)) {
finalValue += Character.toString(valueChar);
}
else {
while (positions.get(0) == positions.get(2) || positions.get(1) == positions.get(2)) {
index = randomGenerator.nextInt(passcode.length());
valueChar = value.charAt(index);
positions.add(index);
}
}
}
}
System.out.println(finalValue + " " + positions);
}
Is there any optimization that could happen or any other suggested approach?
Thanks in advance.