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);
}
}