简体   繁体   中英

find all possible combinations of a set in java

okay so we basically have this question to answer, but I am very confused and don't know how to use recursion to get all possible combinations.. Please someone save me!

Write a public static method threadings , which takes an int n (representing the number of beads on each necklace) and a Set of Strings (representing the available bead colours ; your code must not alter this Set),and returns a Set of ArrayLists of Strings , representing all the orders in which n beads of the given colours can be threaded. If n < 1 , return a Set containing just one, empty, ArrayList .

Examples of correct behaviour:

threadings(0, {red,green}) = {[]}

threadings(1, {red,green}) = {[red],[green]}

threadings(2, {red,green}) = {[red,red],[red,green],[green,red],[green,green]}

threadings(3, {red}) = {[red,red,red]}

Hint: you will probably want threadings to call itself recursively, although full marks are available for any correct method.

This is what I have written until now:

 public static HashSet<ArrayList<String>> threadings (int n, Set<String> colours){
    HashSet<ArrayList<String>> result= new HashSet<ArrayList<String>>();
    ArrayList<String> inresult= new ArrayList<String>();
    String[] col= new String[colours.size()];
    if (n==0){
        result.add(inresult);
        return result;
    }else{

    }
}

Try this:

public static HashSet<ArrayList<String>> threadings (int n, Set<String> colours) {
    List<String> colorsList = new ArrayList<>(colours);
    ArrayList<String> resultList = new ArrayList<>();
    HashSet<ArrayList<String>> result = new HashSet<ArrayList<String>>();
    int carry;
    int[] indices = new int[n];
    do
    {
        for(int index : indices) {
            resultList.add(colorsList.get(index));
        }
        result.add(resultList);
        resultList = new ArrayList<>();

        carry = 1;
        for(int i = indices.length - 1; i >= 0; i--)
        {
            if(carry == 0)
                break;

            indices[i] += carry;
            carry = 0;

            if(indices[i] == colorsList.size())
            {
                carry = 1;
                indices[i] = 0;
            }
        }
    }
    while(carry != 1);

    return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM