SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Recursion
Exercise:
Programming Projects
Question:10 | ISBN:9780132830317 | Edition: 5

Question

Given the definition of a 2D array such as the following,

String[][] data = {

{"A", "B"},

{"1", "2"},

{"XX","YY","ZZ"}

};

write a recursive program that outputs all combinations of each subarray in order. In the previous example, the desired output (although it does not have to be in this order) is

A 1 XX

A 1 YY

A 1 ZZ

A 2 XX

A 2 YY

A 2 ZZ

B 1 XX

B 1 YY

B 1 ZZ

B 2 XX

B 2 YY

B 2 ZZ

Your program should work with arbitrarily sized arrays in either dimension. For

example, the following data

String[][] data = {

{"A"},

{"1"},

{"2"},

{"XX","YY"}

};

should output:

A 1 2 YY

A 1 2 YY


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

PROGRAM CODE:

public class Test Demo
{

    // Recursive method to print all combinations of the 2D array
    private static void printCombinations(String[][] data, String[] currentCombination, int level)
    {
        // If the level reaches the number of rows in the 2D array, we have a complete combination
        if (level == data.length)
        {
            for (String value : currentCombination)
            {
                System.out.print(value + " ");
            }
            System.out.println();
            return;
        }

        // Loop through the elements of the current row and recursively call for the next level
        for (String item : data[level]) {
            currentCombination[level] = item;
            printCombinations(data, currentCombination, level + 1);
        }
    }

    public static void main(String[] args)
    {
        String[][] data = {
            {"A", "B"},
            {"1", "2"},
            {"XX", "YY", "ZZ"}
        };

        // Calculate the total number of combinations and initialize the array
        //to store the current combination
        int totalCombinations = 1;
        for (String[] row : data) {
            totalCombinations *= row.length;
        }
        String[] currentCombination = new String[data.length];

        // Print all combinations
        printCombinations(data, currentCombination, 0);
    }
}

OUTPUT:

A 1 XX 
A 1 YY 
A 1 ZZ 
A 2 XX 
A 2 YY 
A 2 ZZ 
B 1 XX 
B 1 YY 
B 1 ZZ 
B 2 XX 
B 2 YY 
B 2 ZZ 

 

0 0

Discussions

Post the discussion to improve the above solution.