Print all combinations of phrases that can be formed by picking words from each of the given lists

Given N lists of words, print all combinations of phrases that can be formed by picking one word each from each of the given lists.

 

For example,


Input:  

list 1 -> [ John, Emma, Chloe ]
list 2 -> [ Plays, Hates, Watches ]
list 3 -> [ Cricket, Soccer, Chess ]

Output:

John Plays Cricket
John Plays Soccer
John Plays Chess
John Hates Cricket
John Hates Soccer
John Hates Chess
John Watches Cricket
John Watches Soccer
John Watches Chess
Emma Plays Cricket
Emma Plays Soccer
Emma Plays Chess
Emma Hates Cricket
Emma Hates Soccer
Emma Hates Chess
Emma Watches Cricket
Emma Watches Soccer
Emma Watches Chess
Chloe Plays Cricket
Chloe Plays Soccer
Chloe Plays Chess
Chloe Hates Cricket
Chloe Hates Soccer
Chloe Hates Chess
Chloe Watches Cricket
Chloe Watches Soccer
Chloe Watches Chess

 


 

The idea is to use recursion. At each point in the recursion, we consider each word in current list and append the word to output one by one, recurse for next list. Finally, when no list is left to recuse (i.e. all lists are considered), we print the output phase.

 
C++ implementation –
 

Download   Run Code

Output:

John Plays Cricket
John Plays Soccer
John Plays Chess
John Hates Cricket
John Hates Soccer
John Hates Chess
John Watches Cricket
John Watches Soccer
John Watches Chess
Emma Plays Cricket
Emma Plays Soccer
Emma Plays Chess
Emma Hates Cricket
Emma Hates Soccer
Emma Hates Chess
Emma Watches Cricket
Emma Watches Soccer
Emma Watches Chess

 
 

Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz