性能改进的建议Java代码

时间:2017-01-07 08:35:09

标签: java algorithm combinations

你好,我只是为了好玩而这样做,我想弄清楚是否有更有效/更快的方法来做到这一点。对给定的数字和字母列表进行所有可能的组合,然后将它们打印到文本文件中。我目前有这个,我正在寻找建议。

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

public class combos {

  public static void main(String[] args){

     char[] alphabet = new char[] {'0','1','2','3','4','a','b','c','d','e'};

     StringExcersise.possibleStrings(5, alphabet,"");
  }
  } class StringExcersise {
     public static void possibleStrings(int maxLength, char[] alphabet, String curr){

        if(curr.length() == maxLength) {
          try (PrintWriter out = new PrintWriter(new FileWriter("./Combos.txt", true))) {
          out.println(curr);
          }catch (IOException e) {
          System.err.println(e);}

        } else {
          for(int i = 0; i < alphabet.length; i++) {
              String oldCurr = curr;
              curr += alphabet[i];
              possibleStrings(maxLength,alphabet,curr);
              curr = oldCurr;
            }
        }
    }
}

目前我需要大约26秒才能运行。

2 个答案:

答案 0 :(得分:1)

最大的性能瓶颈是IO。每次打开/关闭文件都非常昂贵。我建议你打开一个。此外,您不需要首先创建集合,因为随着集合的增长,这会变得很昂贵,只需在计算时将结果写入缓冲文件。

您可以通过构建char[]而不是String并打印char []来获得相对较小的改进。

class StringExercise {
    static void possibleStrings(char[] alphabet, PrintWriter pw, char[] curr, int index) {
        if (index == curr.length) {
            pw.println(curr);
            return;
        }
        for (char c : alphabet) {
            curr[index] = c;
            possibleStrings(alphabet, pw, curr, index + 1);
        }
    }
}

public class Combos {
    public static void main(String[] args) throws FileNotFoundException {
        long start = System.currentTimeMillis();
        try (PrintWriter pw = new PrintWriter("combos.txt")) {
            StringExercise.possibleStrings("01234abcde".toCharArray(), pw, new char[5], 0);
        }
        System.out.printf("Took %.3f seconds to run%n", (System.currentTimeMillis()-start)/1e3);
    }
}

打印

Took 0.030 seconds to run

我检查过它会产生预期的输出。

答案 1 :(得分:0)

最后写入文件并用尾递归替换递归会将时间缩短到不到1秒:

public static void main(String[] args)
{
    char[] alphabet = new char[]{'0', '1', '2', '3', '4', 'a', 'b', 'c', 'd', 'e'};

    Set<String> permutations = new HashSet<>();
    possibleStrings(5, alphabet, "", permutations);

    try (PrintWriter out = new PrintWriter(new FileWriter("./Combos.txt", true)))
    {
        out.println(permutations);
    }
    catch (IOException e)
    {
        System.err.println(e);
    }
}

public static void possibleStrings(int maxLength, char[] alphabet, String curr, Set<String> permutations)
{
    if (curr.length() == maxLength)
    {
        permutations.add(curr);
    }
    else
    {
        for (char anAlphabet : alphabet)
        {
            possibleStrings(maxLength, alphabet, curr + anAlphabet, permutations);
        }
    }
}