Combination of a list - no repeats, specify length

I've been spending quite some time on a problem that I hoped would be fairly straightforward.

I want to populate a list of integers based on the combinations of another list of integers. There can't be any repeats and I want to be able to specify the length of combinations, for example:

List: {0, 1, 2}

Combinations with a length of 1: {0}, {1}, {2}

Combinations with a length of 2: {0, 1}, {0, 2}, {1, 2}

Combinations with a length of 3: {0, 1, 2}

The original list may not always have a length of 3, I just used that as an easy example. Could someone please help me with a way to do this, in C#? I've found numerous examples online, but they either use NET functions which I can't use in Unity, or don't do one of the things I want (no repeats, specify length).

1 Reply

That's actually quite simple. All you need to do is using as many nested for loops as you want numbers in your combination and let the inner loops start at the current outer loop +1. The easiest way would probably be a recursive method if you want to have the combination length variable.

here combinations will contain all combinations with 2 elements of the given list. I've actually tested it with the following code. If does actually print all combinations. The two foreach loops are just to convert the lists into a nice printable form.

This is beautiful! Thanks so much for taking the time to help. Having tested it it looks to be exactly what I want. I've also compared results against an online combination calculator and results are identical.

Thanks again.

Your answer

Hint: You can notify a user about this post by typing @username

Attachments:
Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.