Ibrahem Uwk Ibrahem Uwk - 29 days ago 5
Java Question

how can i make this java program run in multi core?

this program is to generate all possible strings from given char sequance with given set but it take much time
so how can i run it in multi cpu??


this program is to generate all possible strings from given char sequance with given set but it take much time
so how can i run it in multi cpu??



public class LapTest {

static int q=0;

public static void main(String[] args) {
System.out.println("First Test");
char set1[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
int k = 4;
printAllKLength(set1, k);

System.out.println(q);
}

// The method that prints all possible strings of length k. It is
// mainly a wrapper over recursive function printAllKLengthRec()
static void printAllKLength(char set[], int k) {
int n = set.length;
printAllKLengthRec(set, "", n, k);
}

// The main recursive method to print all possible strings of length k
static void printAllKLengthRec(char set[], String prefix, int n, int k) {

// Base case: k is 0, print prefix
if (k == 0) { q++;
System.out.println(prefix);

if (prefix.equals("hkka")) {
System.exit(0);
}
return;
}

// One by one add all characters from set and recursively
// call for k equals to k-1
for (int i = 0; i < n; ++i) {

// Next character of input added
String newPrefix = prefix + set[i];

// k is decreased, because we have added a new character
printAllKLengthRec(set, newPrefix, n, k - 1);
}
}
}

Answer

There are many performance improvements you should make before you try to make it multi-threaded. I can see several obvious things you could do to improve performance. But experience has shown that most coders (myself included) are terrible at guessing where code should be tweaked to make it more efficient.

So my advice is to learn to use a profiler. Profile your code and find out where it is spending cpu cycles then tweak the code in the right places. You will get much better results learning to do that. Good modern IDEs make this a pretty simple process for simple programmes.