Sunday, December 21, 2014

Print combinations of strings from List of List of Strings

Print combinations of strings from List of List of Strings.
Example input: [[abc, def], [ghi, jkl, mno], [pqr]]
Example output:
abc ghi pqr 
abc jkl pqr 
abc mno pqr 
def ghi pqr 
def jkl pqr 
def mno pqr 

Java Program

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Combinations {
 public static void main(String[] args) {
  int num = 0;
  ArrayList<List<String>> input = new ArrayList<List<String>>();
  input.add(Arrays.asList("abc","def"));
  input.add(Arrays.asList("ghi","jkl","mno"));
  input.add(Arrays.asList("pqr"));
  ArrayList<String> output = new ArrayList<String>();
  combine(num, input, output);
 }
 
 public static void combine(int num, ArrayList<List<String>> input, ArrayList<String> output) {
  if(num == input.size()) {
   for(String string : output) {
    System.out.print(string + " ");
   }
   System.out.println();
  }
  else {
   List<String> current = input.get(num);
   for(String string : current) {
    output.add(string);
    combine(num + 1, input, output);
    output.remove(num);
   }
  }
 }
}

No comments:

Post a Comment