Given a list of arrays, find all combinations where each combination contains one element from each given array.
Examples:
Input : [ [1, 2], [3, 4] ]
Output : 1 3
1 4
2 3
2 4
Input : [ [1], [2, 3, 4], [5] ]
Output : 1 2 5
1 3 5
1 4 5
We keep an array of size equal to the total no of arrays. This array called indices helps us keep track of the index of the current element in each of the n arrays. Initially, it is initialized with all 0s indicating the current index in each array is that of the first element. We keep printing the combinations until no new combinations can be found. Starting from the rightmost array we check if more elements are there in that array. If yes, we increment the entry for that array in indices i.e. moves to the next element in that array. We also make the current indices 0 in all the arrays to the right of this array. We keep moving left to check all arrays until one such array is found. If no more arrays are found we stop there.
C++
// C++ program to find combinations from n // arrays such that one element from each // array is present#include <bits/stdc++.h>using namespace std;// function to print combinations that contain// one element from each of the given arraysvoid print(vector<vector<int> >& arr){ // number of arrays int n = arr.size(); // to keep track of next element in each of // the n arrays int* indices = new int[n]; // initialize with first element's index for (int i = 0; i < n; i++) indices[i] = 0; while (1) { // print current combination for (int i = 0; i < n; i++) cout << arr[i][indices[i]] << " "; cout << endl; // find the rightmost array that has more // elements left after the current element // in that array int next = n - 1; while (next >= 0 && (indices[next] + 1 >= arr[next].size())) next--; // no such array is found so no more // combinations left if (next < 0) return; // if found move to next element in that // array indices[next]++; // for all arrays to the right of this // array current index again points to // first element for (int i = next + 1; i < n; i++) indices[i] = 0; }}// driver function to test above functionint main(){ // initializing a vector with 3 empty vectors vector<vector<int> > arr(3, vector<int>(0, 0)); // now entering data // [[1, 2, 3], [4], [5, 6]] arr[0].push_back(1); arr[0].push_back(2); arr[0].push_back(3); arr[1].push_back(4); arr[2].push_back(5); arr[2].push_back(6); print(arr);} |
Java
// Java program to find combinations from n // arrays such that one element from each // array is presentimport java.util.*;class GFG{// Function to print combinations that contain// one element from each of the given arraysstatic void print(Vector<Integer> []arr){ // Number of arrays int n = arr.length; // To keep track of next element in // each of the n arrays int []indices = new int[n]; // Initialize with first element's index for(int i = 0; i < n; i++) indices[i] = 0; while (true) { // Print current combination for(int i = 0; i < n; i++) System.out.print( arr[i].get(indices[i]) + " "); System.out.println(); // Find the rightmost array that has more // elements left after the current element // in that array int next = n - 1; while (next >= 0 && (indices[next] + 1 >= arr[next].size())) next--; // No such array is found so no more // combinations left if (next < 0) return; // If found move to next element in that // array indices[next]++; // For all arrays to the right of this // array current index again points to // first element for(int i = next + 1; i < n; i++) indices[i] = 0; }}// Driver codepublic static void main(String[] args){ // Initializing a vector with 3 empty vectors @SuppressWarnings("unchecked") Vector<Integer> []arr = new Vector[3]; for(int i = 0; i < arr.length; i++) arr[i] = new Vector<Integer>(); // Now entering data // [[1, 2, 3], [4], [5, 6]] arr[0].add(1); arr[0].add(2); arr[0].add(3); arr[1].add(4); arr[2].add(5); arr[2].add(6); print(arr);}}// This code is contributed by amal kumar choubey |
Python3
# Python3 program to find combinations from n # arrays such that one element from each # array is present# function to prcombinations that contain# one element from each of the given arraysdef print1(arr): # number of arrays n = len(arr) # to keep track of next element # in each of the n arrays indices = [0 for i in range(n)] while (1): # prcurrent combination for i in range(n): print(arr[i][indices[i]], end = " ") print() # find the rightmost array that has more # elements left after the current element # in that array next = n - 1 while (next >= 0 and (indices[next] + 1 >= len(arr[next]))): next-=1 # no such array is found so no more # combinations left if (next < 0): return # if found move to next element in that # array indices[next] += 1 # for all arrays to the right of this # array current index again points to # first element for i in range(next + 1, n): indices[i] = 0# Driver Code# initializing a vector with 3 empty vectorsarr = [[] for i in range(3)]# now entering data# [[1, 2, 3], [4], [5, 6]]arr[0].append(1)arr[0].append(2)arr[0].append(3)arr[1].append(4)arr[2].append(5)arr[2].append(6)print1(arr)# This code is contributed by mohit kumar |
C#
// C# program to find // combinations from n // arrays such that one // element from each // array is presentusing System;using System.Collections.Generic;class GFG{// Function to print combinations // that contain one element from // each of the given arraysstatic void print(List<int> []arr){ // Number of arrays int n = arr.Length; // To keep track of next // element in each of // the n arrays int []indices = new int[n]; // Initialize with first // element's index for(int i = 0; i < n; i++) indices[i] = 0; while (true) { // Print current combination for(int i = 0; i < n; i++) Console.Write(arr[i][indices[i]] + " "); Console.WriteLine(); // Find the rightmost array // that has more elements // left after the current // element in that array int next = n - 1; while (next >= 0 && (indices[next] + 1 >= arr[next].Count)) next--; // No such array is found // so no more combinations left if (next < 0) return; // If found move to next // element in that array indices[next]++; // For all arrays to the right // of this array current index // again points to first element for(int i = next + 1; i < n; i++) indices[i] = 0; }}// Driver codepublic static void Main(String[] args){ // Initializing a vector // with 3 empty vectors List<int> []arr = new List<int>[3]; for(int i = 0; i < arr.Length; i++) arr[i] = new List<int>(); // Now entering data // [[1, 2, 3], [4], [5, 6]] arr[0].Add(1); arr[0].Add(2); arr[0].Add(3); arr[1].Add(4); arr[2].Add(5); arr[2].Add(6); print(arr);}}// This code is contributed by shikhasingrajput |
Output:
1 4 5 1 4 6 2 4 5 2 4 6 3 4 5 3 4 6
This article is contributed by aditi sharma 2. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- itertools.combinations() module in Python to print all possible combinations
- Maximum sum by picking elements from two arrays in order
- Maximum sum from three arrays such that picking elements consecutively from same is not allowed
- Maximum sum by picking elements from two arrays in order | Set 2
- Check if an Array can be Sorted by picking only the corner Array elements
- Maximum area rectangle by picking four sides from array
- Maximize the sum of X+Y elements by picking X and Y elements from 1st and 2nd array
- Form an array of distinct elements with each element as sum of an element from each array
- Ways to divide a binary array into sub-arrays such that each sub-array contains exactly one 1
- K maximum sum combinations from two arrays
- Sum of product of each element with each element after it
- Find Array formed by adding each element of given array with largest element in new array to its left
- Array formed from difference of each element from the largest element in the given array
- Find just strictly greater element from first array for each element in second array
- Iterating over all possible combinations in an Array using Bits
- Iterative approach to print all combinations of an Array
- Range Query on array whose each element is XOR of index value and previous element
- Replace each element by the difference of the total size of the array and frequency of that element
- Modify given array by reducing each element by its next smaller element
- Maximum sum in an array such that every element has exactly one adjacent element to it

