-1

I want to generate string of given length, from given characters. The order of the characters matters, also I want to use multiple threads to generate it. Here are a few examples:

chars: a,b,c,d
length: 1
output: 
a
b
c
d
chars: a,b,c,d
length: 2
output:
aa
ab
ac
ad
bb
ba
bc
bd
cc
ca
cb
cd
dd
da
db
dc

I've tried this algorithm: Note: it's pseudo-code

func generate(set, str, k){
    if (k == 0){
        print str;
        return;
    }
    for (c in set) {
        newString = str + c;
        generate(set, newString, k-1);
    }
}

However I don't see how to use multiple threads. All other algorithms I've read about don't suite my needs.

Deyan Georgiev
  • 343
  • 3
  • 15

1 Answers1

0

No need of use multithreading for this algorithm. The for loop is only for generating string for required length. In java the code is like this.

import java.util.Random;

public class RandomString2 {

static String[] option = {"a","b","v","k"}; 

static String getRandomElement()
{
    int idx = new Random().nextInt(option.length);
    return option[idx];
}

static String getRandomString(int length)
{
    String result="";
    for(int i = 1; i<=length ; i++)
    {
        result += getRandomElement();
    }
    return result;
}

public static void main(String[] args) {
    // TODO Auto-generated method stub

    System.out.println(getRandomString(5));  // pass string length as parameter

}

}
Shahbaz Hashmi
  • 2,631
  • 2
  • 26
  • 49
  • I want to make the algorithm multi threaded, since I'm planning to use it for a lot of combinations. – Deyan Georgiev Jul 06 '16 at 18:11
  • I dont know what are you planning to execute. But multithreading is used for separate path of execution. I had answered to your particular question. It will be better that u post some code. – Shahbaz Hashmi Jul 06 '16 at 18:19
  • Well it's possible that I have so misunderstaning of what multithreading is. However what I want is to split the computation between multiple threads/processors, so that I can compute the result faster. – Deyan Georgiev Jul 06 '16 at 18:50