The following code is itself in an outer loop where oldChar
is defined:
List<Character> modifiableCollection = new ArrayList<Character>(Arrays.asList(AlphabeticalStatistics.ALL_LETTERS));
for (int j = 0; j < modifiableCollection.size(); j++) {
Character letterOfAlphabet = modifiableCollection.get(j);
String loaAsString = letterOfAlphabet.toString();
if (replaceLetters(Character.toString(oldChar), loaAsString)) {
modifiableCollection.remove(j);
System.out.println(oldChar + " was replaced with " + loaAsString);
break;
}
}
I am trying to iterate through ALL_LETTERS
as efficiently as possible. For each element, I want to check if replaceLetters()
on that letter and another letter. If so, the letter will be replaced and I want to remove this from the modifiableCollection
so the next time this is looped it won't look to replace that letter again.
However, what I am seeing is using an enhanced for loop WITH REMOVAL, the code runs AND is more efficient. I must not remove in an enhanced for:
for (Character letterOfAlphabet : modifiableCollection) {...remove()} // Compiles
, but when I use a regular for loop, like above, the program takes longer to run; when I use iterator, the program takes even longer to run. Should I stick to the foreach loop?
Edit
replaceLetters()
method:
protected boolean replaceLetters(String toReplace, String replacement, String toAdd, String toAdd2) {
if (replacedLetters.contains(toAdd2) || solvedLetters.contains(toAdd))
return false;
return isCorrect(toReplace, replacement, toAdd, toAdd2);
}
private boolean isCorrect(String toReplace, String replacement, String toAdd, String toAdd2) {
String newText = getText().replace(toReplace, replacement);
if (Arrays.stream(newText.split(" "))
.filter(w -> {
return w.contains(replacement) && AlphabeticalStatistics.needsNoLetters(w);
})
.noneMatch(w -> {
return !EnglishDeterminer.isWord(w);
})
) {
setText(newText);
solvedLetters.add(toAdd);
replacedLetters.add(toAdd2);
return true;
}
return false;
}
The purpose of this program is to decipher a substitution ciphertext.