Iterate to find all combinations of character array size k (N chooses K)


seafarer

I'm currently working on this as a personal project.

basically:

  • Given an array of elements such as E = {1,2,a,b} and
  • Given a number K, for example K = 2
  • I want to return all E combinations of size E (E chooses K)
  • For example {{1,1},{1,2},{1,a},{1,b},{2,1},...,{b,1},{b,2},{b , a}, {b, b}}

I've achieved this recursively using the following function:

char[] pool = new char[]{'1', '2', '3'};

public void buildStringRec(char[] root, int pos, int length){
    for(char c : pool){
        char[] newRoot = root.clone();
        newRoot[pos] = c;
        if(pos+1 < length){
            buildStringRec(newRoot, pos+1, length);
        } else{
            System.out.println(String.valueOf(root));
        }
    }
}

poolWhere is E and where is lengthK.

So we call it: buildStringRec(new char[2], 0, 2);and get

11
12
13
21
22
23
31
32
33

Can it be done iteratively? I've been trying to wrap my head around how to do this with variable length.

Any help would be greatly appreciated! I can post my code as-is if needed, but it changes so frequently due to retries that it's almost useless as soon as I post it.

Also, I don't want to use Apache or String Builder to do this because I want to understand the concept of how to do it. I'm not just asking for code. Pseudocode is fine as long as it is explicitly stated.

Thanks!

edit

I'm using this site to test all the options offered to me: https://ideone.com/k1WIa6
Feel free to try it out and give it a try!

Sagmark

Here is another iterative solution:

You can create an array of integers of size K to use as a counter to keep track of distances passed through the combination, and a char array to store the current combination.

After printing each one, move on to the next combination by incrementing the counter value, if it "overflows" by reaching a value equal to the number of elements in E, reset it to zero and perform a carry by incrementing the counter In the next position, also check there for overflow and so on. Kind of like an odometer in a car, except the numbers are related to the values ​​in E. Once the last position overflows, all possible combinations are generated.

I increment the counter starting at the last value of the array and move down to get the same output as your example, but that's certainly not required. The algorithm does not check for duplicates.

You don't have to store the character array with the current combination, you can regenerate it each time in a counter-based for loop, but that might be less efficient. This method only updates the changed value.

public static void buildStrings(char[] root, int length)
{
    // allocate an int array to hold the counts:
    int[] pos = new int[length];
    // allocate a char array to hold the current combination:
    char[] combo = new char[length];
    // initialize to the first value:
    for(int i = 0; i < length; i++)
        combo[i] = root[0];

    while(true)
    {
        // output the current combination:
        System.out.println(String.valueOf(combo));

        // move on to the next combination:
        int place = length - 1;
        while(place >= 0)
        {
            if(++pos[place] == root.length)
            {
                // overflow, reset to zero
                pos[place] = 0;
                combo[place] = root[0];
                place--; // and carry across to the next value
            }
            else
            {
                // no overflow, just set the char value and we're done
                combo[place] = root[pos[place]];
                break;
            }
        }
        if(place < 0)
            break;  // overflowed the last position, no more combinations
    }
}

ideone.com demo

Related


Find all combinations of size at least k to n

Vietnam's I am struggling to figure out the formula to solve this problem: Given an array of nnumbers and a limit k, count all distinct combinations of at least size .k E.g:A=[1,2,3] k = 2 output = 4 // [1,2],[1,3],[1,2,3],[2,3] The array can contain repeated

Find all combinations of size at least k to n

Vietnam's I am struggling to figure out the formula to solve this problem: Given an array of nnumbers and a limit k, count all distinct combinations of at least size .k E.g:A=[1,2,3] k = 2 output = 4 // [1,2],[1,3],[1,2,3],[2,3] The array can contain repeated

Find all combinations of size at least k to n

Vietnam's I am struggling to figure out the formula to solve this problem: Given an array of nnumbers and a limit k, count all distinct combinations of at least size .k E.g:A=[1,2,3] k = 2 output = 4 // [1,2],[1,3],[1,2,3],[2,3] The array can contain repeated

Find all combinations of size at least k to n

Vietnam's I am struggling to figure out the formula to solve this problem: Given an array of nnumbers and a limit k, count all distinct combinations of at least size .k E.g:A=[1,2,3] k = 2 output = 4 // [1,2],[1,3],[1,2,3],[2,3] The array can contain repeated

Find all combinations of size at least k to n

Vietnam's I am struggling to figure out the formula to solve this problem: Given an array of nnumbers and a limit k, count all distinct combinations of at least size .k E.g:A=[1,2,3] k = 2 output = 4 // [1,2],[1,3],[1,2,3],[2,3] The array can contain repeated

Find all combinations of size at least k to n

Vietnam's I am struggling to figure out the formula to solve this problem: Given an array of nnumbers and a limit k, count all distinct combinations of at least size .k E.g:A=[1,2,3] k = 2 output = 4 // [1,2],[1,3],[1,2,3],[2,3] The array can contain repeated

Find all combinations of size at least k to n

Vietnam's I am struggling to figure out the formula to solve this problem: Given an array of nnumbers and a limit k, count all distinct combinations of at least size .k E.g:A=[1,2,3] k = 2 output = 4 // [1,2],[1,3],[1,2,3],[2,3] The array can contain repeated

all possible combinations of k with lists of size n

Theodore Narliyski: I want to get all possible combinations of size K from a list of size N. I have a list with "person" objects and I am trying to create a new ArrayList which will be filled with the list of objects. Each table will be a different combination

all possible combinations of k with lists of size n

Theodore Narliyski: I want to get all possible combinations of size K from a list of size N. I have a list with "person" objects and I am trying to create a new ArrayList which will be filled with the list of objects. Each table will be a different combination

Get all n-size combinations with k-size letters

Scion 4581 Can someone help me? I am trying to find the formula and write a piece of code in PHP language which makes the next step Imagine we have 3 types of things, k = 1, 2, 3, and the length of this number can be different (n length), but adjacent types sh

make all combinations of size k from 1 to number n

Ananya Given two numbers n and k, you have to find all possible combinations of k numbers in 1...n. I am using DFS algorithm to achieve this. But my ansarray returns None, whereas if I try to print temp, the combination is generated correctly. What am I doing

make all combinations of size k from 1 to number n

Ananya Given two numbers n and k, you have to find all possible combinations of k numbers in 1...n. I am using DFS algorithm to achieve this. But my ansarray returns None, whereas if I try to print temp, the combination is generated correctly. What am I doing

Find all unique combinations of n numbers between 1 and k

Onoga I want a list containing all possible sets of five (or n) numbers between 1 and 63 (or more generally 1 and k) If computation time is not an issue, I can do something like #Get all combenations of numbers between 1 and 63 indexCombinations <- expand.gr

Algorithm to generate n combinations of size k characters

alex_and_ra I need an algorithm that generates all combinations of size n of k characters. For example, if I have n=1 and k={a,b}, the result should be: a b If n=3 and k={a,b}, the result should be: a a a a a b a b a a b b b a a b a b b b a b b b Can someone

Algorithm to generate n combinations of size k characters

alex_and_ra I need an algorithm that generates all combinations of size n of k characters. For example, if I have n=1 and k={a,b}, the result should be: a b If n=3 and k={a,b}, the result should be: a a a a a b a b a a b b b a a b a b b b a b b b Can someone

All possible combinations of N objects in K buckets

Aliresa Norri Say I have 3 boxes labeled A, B, C and I have 2 balls, B1 and B2. I want to get all possible combinations of these balls in a box. Note that it is important to know the balls in each box, which means that B1 and B2 are not the same. A B