Question

I'm writing a program, that must find all combination:

String[] combination = new String[]{"123,"12","34"};

application must return:

113
114
123
124
213
214
223
224
313
314
323
324

There will be 81 elementnts at max in array per most of 9 character to make combination with they. So first digit must be from com[0], second from com[1] and so on.

Thx for help!

Was it helpful?

Solution

Well here's one way to do it (maybe a slightly 'ugly hack' in places)! Obviously it needs to be generalised to handle different input strings, but that should be trivial enough.

EDIT: I've made a few alterations so its closer to something dynamic, but the user input handling still remains to be done: at the moment only there's just a single 'input' array, as you can see.

package combinations;

import java.util.ArrayList;

public class Combinations {

    static String[] combination = {"123","12","34"};

    public static void main(String[] args) {

        Combinations combinations = new Combinations();

        ArrayList<String> string = new ArrayList<String>();
        ArrayList<String> input = new ArrayList<String>();

        input = combinations.stringDecomposition(combination[0]);
        string = combinations.combinations(input,combination[1]);

        // next for loop starts from index i = 2 since result of combining first 2 elements
        // has just been calculated in the last line 

        for(int i = 2; i<combination.length; i++)
        {
            string = combinations.combinations(string,combination[i]);
        }

        for(int i = 0; i<string.size(); i++)
        {
            System.out.println(string.get(i));
        }

    }


        public ArrayList<String> combinations(ArrayList<String> input0, String input1){

            ArrayList<String> result = new ArrayList<String>();

                int jlength = input1.length();

                for(int i=0; i<input0.size(); i++)
                {

                        for(int j=0; j<jlength; j++)
                        {

                            StringBuilder stringBuilder = new StringBuilder();
                            stringBuilder.append(input0.get(i));
                            stringBuilder.append(input1.charAt(j));
                            result.add(stringBuilder.toString());   
                        }

                }

            return result;

        }

        public ArrayList<String> stringDecomposition(String in){

            ArrayList<String> result = new ArrayList<String>();

            for(int i =0;i<in.length();i++){
                StringBuilder s = new StringBuilder();
                s.append(in.charAt(i));
                result.add(s.toString());               
            }

            return result;

        }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top