Skip to content

Instantly share code, notes, and snippets.

@hr1383
Created April 20, 2015 04:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hr1383/d9078aec997de34dab02 to your computer and use it in GitHub Desktop.
Save hr1383/d9078aec997de34dab02 to your computer and use it in GitHub Desktop.
Given a list of word lists How to print all sentences possible taking one word from a list at a time via recursion
// Given a list of word lists How to print all sentences possible taking one word from a list at a time via recursion
// http://www.geeksforgeeks.org/recursively-print-all-sentences-that-can-be-formed-from-list-of-word-lists/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class RecursiveList {
public static void main(String[] args) {
List<String> l1 = Arrays.asList(new String[]{"you","are"});
List<String> l2 = Arrays.asList(new String[]{"1","2"});
List<String> l3 = Arrays.asList(new String[]{"@","#","$"});
List<List<String>> l4 = new ArrayList<List<String>>(3);
l4.add(l1);l4.add(l2);l4.add(l3);
print(l4,"",0);
}
public static void print(List<List<String>> list, String output, int listIndex) {
if(listIndex == list.size()) {
System.out.println(output);
return;
}
List<String> curr = list.get(listIndex);
for(String str: curr) {
print(list, output+" " + str, listIndex+1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment