-3

I am having difficulty creating some general for loops on my own (my code is in java). Imagine I have M number of arraylists of strings that each arraylist s_i has x_i members. I want to generate all possible strings such that the first part of string is from first set, the second part of string is from second set and ...

For example, below, there are 3 lists (which is unknown at time of programming):

|s_0| = x_0 = 3: [a1, a2, a3]

|s_1| = x_1 = 5: [b1, b2, b3, b4, b5]

|s_2| = x_2 = 2: [c1, c2]

I want to generate these strings (order is not important):

strings: ["a1 b1 c1", "a1 b1 c2", "a1 b2 c1", ...., "a3 b5 c2"]

karakfa
  • 66,216
  • 7
  • 41
  • 56
sinderela
  • 65
  • 5
  • You want all permutations of them? – 3kings Oct 30 '15 at 20:46
  • Possible duplicate of [How to generate in PHP all combinations of items in multiple arrays](http://stackoverflow.com/questions/8567082/how-to-generate-in-php-all-combinations-of-items-in-multiple-arrays) – Timofey Oct 30 '15 at 21:13
  • 1
    Hint: Define a cross product between two sets and generalize to three. – karakfa Oct 30 '15 at 21:33

1 Answers1

1

You can use Guava Sets. For example this will give all combinations AAA, AAB,...,CCC.

final Set<String> set = new HashSet<>();
set.add("A");
set.add("B");
set.add("C");
final Set<List<String>> sets = Sets.cartesianProduct(set, set, set);

In your case you will have to pass s_0, s_1, s_2 for the parameters.

mvd
  • 2,596
  • 2
  • 33
  • 47