Java combination

I need to find a combination combination in JAVA.

For example, I have 6 students in a class. Of these, I need to create a group of 4 people in a group, and for each group I can choose an intimate group of 2.

I have to make sure there are no doubles (order doesn't matter).! and you need to print a group of 4 people.

However, this is the hard part:

Thus, the definition of students with numbers:

If I print 1234 as one of the combinations, I cannot print 1256, since it 12appears both in 1234and 1256.

How can I write it in Java?

EDITED

output ([1,2,3,4,5], 3,2) will be:

  • Combinations without repetition (n = 5, r = 3) {1,2,3} {1,2,4} {1,2,5} {1,3,4} {1,3,5} {1, 4,5} {2,3,4} {2,3,5} {2,4,5} {3,4,5}

  • removing duplicate groups of 2 elements will leave me only: {1,2,3} {1,4,5}(deleted groups that have combinations 12,13,23,45,14,15, since they already appear in the first two that I found.

+3
source share
2 answers

Well, here is a simple emulation of the process you described. But I use binary numbers to represent set, this makes manipulation easier. For example, the number 19 is 10011 in binary form: this means that students 0, 3, and 4 are selected (in these positions 1).

First a little helper.

// return all subsets of 'set', having size 'subsetSize'
Set<Integer> allSubsets(int set, int subsetSize) {
    Set<Integer> result = new HashSet<Integer>();
    if (subsetSize == 0) {
        result.add(0);
        return result;
    }
    if (set == 0) {
        return result;
    }

    // check if 1st element is present
    if (set % 2 == 1) {
        // use 1st element, one less element to collect
        for (Integer i : allSubsets(set / 2, subsetSize - 1)) {
            result.add(i * 2 + 1);
        }
    }
    // not use 1st element
    for (Integer i : allSubsets(set / 2, subsetSize)) {
        result.add(i * 2);
    }

    return result;
}

And the main program. Suggestions are welcome.

    int N = 5;
    int M = 3;
    int Z = 2;

    List<Integer> result = new ArrayList<Integer>();

    // get all groups of M elements from 'wholeSet'
    int wholeSet = (1 << N) - 1;
    for (int s : allSubsets(wholeSet, M)) {
        // Check all subsets of 'Z' elements from set 's'
        boolean valid = true;
        for (int t : allSubsets(s, Z)) {
            // check if this Z-element subset already was used
            for (int past : result) {
                // check if 't' is subset of 'past' set
                if ((past|t) == past) {
                    valid = false;
                    break;
                }
            }
            if (!valid) {
                break;
            }
        }

        if (valid) {
            // none of Z-element subsets of 's' were used before
            result.add(s);
        }
    }

(, memoization) . , , , , .

+1

, Student Primarykey. 1 1, 2 2 ..

, , .

, 4, 2 .

0

Source: https://habr.com/ru/post/1766672/


All Articles