0

I have the following code to write all permutations and combinations in a file but it is taking lot of time to write into a file ... Please suggest better code which have good performance. When I give input abcdefghijklmnopqrstuvwxyz and n=5 then it is taking around 5 min to execute.

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.text.Collator;
import java.util.Arrays;

import java.util.Locale;
import java.util.Scanner;

public class permutation {

    static int c;
    static  Scanner s=new Scanner(System.in);
    static String input =s.nextLine();

    int size = s.nextInt();
    boolean[] num = new boolean[input.length()];

    public void generate(String data) throws Exception {
         FileWriter fstream = new FileWriter("D:\\out.txt",true);
         BufferedWriter out = new BufferedWriter(fstream);
         if (data.length() == size) {
              out.newLine();
              out.write(data);
              System.out.println(data);
              c++;
              out.close();
              return;
         } 
         for (int i = 0; i < input.length(); ++i) {
            if (!num[i]) {
                num[i] = true;
                generate(data + input.charAt(i));                   
                num[i] = false;      
            }

         }
    }


    public static void main(String[] args) throws Exception {
        long startTime = System.currentTimeMillis();
        permutation obj = new permutation();
        Collator col = Collator.getInstance(new Locale("en", "EN"));
        String s = input;
        String[] s1= s.split("");
        Arrays.sort(s1, col);
        String sorted = "";
        for (int i = 0; i < s1.length; i++) {
            sorted += s1[i];
        }
        input=sorted;
        System.out.println(input);
        obj.generate("");
        System.out.println();


        long endTime   = System.currentTimeMillis();
        long totalTime = endTime - startTime;
        System.out.println(totalTime);

    }
}
Nurjan
  • 5,889
  • 5
  • 34
  • 54

1 Answers1

3

If you want to make your code faster, don't repeatedly open and close the file. Open it once at the start of the run and close it once at the end.

Opening a file involves performing at least syscall, and probably thousands of machine instructions. The creation of the BufferedWriter is a few thousand more if you include the cost of the "object churn" of creating and disposing of the buffers. These overheads should be only incurred once ... not moltiple times ... if you want your program to run at a reasonable rate.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Sorry, but this is not a free coding service. I'm guessing that this is homework or some other kind of learning exercise. It that is true, then the point (the WHOLE point, really) of the exercise is that you learn by doing the work for yourself. – Stephen C Oct 17 '16 at 10:35