user3275938 user3275938 - 7 months ago 17
Java Question

What is the fastest way to generate all possibble 6 length string and write to file?

I would like to generate all possible 6 length strings
I need this format:
aaa000
aaa001
...

Here is my code:

private List<String> licensePlateList = new ArrayList<>();
private List<String> numberList = new ArrayList<>();
private List<String> letterList = new ArrayList<>();

public static void main(String[] args) {
Main app = new Main();
long start = System.nanoTime();

app.generateNumbers();
int letters = 26;
int count = 3;
final int combinations = (int) Math.pow(letters, count);
StringBuilder sb = new StringBuilder(count);
for (int i = 0; i < combinations; i++) {
sb.setLength(0);
for (int j = 0, i2 = i; j < count; j++, i2 /= letters)
sb.insert(0, (char) ('a' + i2 % letters));
app.letterList.add(sb.toString());
}

long time = System.nanoTime() - start;
System.out.printf("Took %.3f seconds to generate", time / 1e9);

for (int i=0;i<app.letterList.size();i++){
for (int j=0;j<app.numberList.size();j++){
String licensePlate = app.letterList.get(i)+app.numberList.get(j);
try(FileWriter fw = new FileWriter("licensePlate2.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println(licensePlate);
} catch (IOException e) {
e.printStackTrace();
}
}
}

time = System.nanoTime() - start;
System.out.printf("Took %.3f seconds to generate %,d combinations%n", time / 1e9, app.licensePlateList.size());
}

private void generateNumbers(){
for (int i=0;i<1000;i++){
numberList.add(String.format("%03d", i));
}
}
}


I generate all possible numbers in the generateNumbers() method. In the main() method after I generate numbers I generate all possible 3 length strings into letterList.
After I map every string with numbers and write out to file.

But its really slow. Do you know a faster way?

Answer

Your algorithm is opening a new writer for every licence plate.

Instead, open one writer and write them all to that:

try(FileWriter fw = new FileWriter("licensePlate2.txt", true);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter out = new PrintWriter(bw)) {
    for (String letters : app.letterList) {
        for (String numbers : app.numberList) {
            out.print(letters);
            out.println(numbers);
        }
    }
} catch (IOException e) {
    e.printStackTrace();
}

Note how this code avoids creating an intermediate string for the whole licence number by writing each string separately.

Note also the use of "for each" loops.