Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

c# - How to get all the unique n-long combinations of a set of duplicatable elements?

I have found many solutions giving a collection elements combined in all possible orders but they all use every element just once in every result while I need them to be treated as reusable.

For example if input elements are {"a", "b", "c"} and the number is 2 the output is to be {"a", "a"}, {"a", "b"}, {"a", "c"}, {"b", "a"}, {"b", "b"}, {"b", "c"}, {"c", "a"}, {"c", "b"}, {"a", "c"}.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Lets say you've got N input elements, and you want a K-long combination.

All you need to do is to count in base N, scoped of course, to all numbers that have K digits.

So, lets say N = {n0, n1, ... nN}

You'd start from the number [n0 n0 ... n0], and count all the way up to [nN nN ... nN]

If you'd like help in understanding how to count in another base, you can get that here

Each number that you compute maps to one of the K-long combinations that you need.

I think an example will help

I'll use your values. N = {a, b, c} So we want to count in base 3. Since we want 2-long combinations, we only care about 2-digit numbers. The smallest 2-digit base 3 number is 00, so we start there. By counting in base 3, we get:

00
01
02
10
11
12
20
21
22

Ok, so now to convert these numbers into a combination.

Remember, our set is {a, b, c}

So whenever we see a 0, it implies 1. Wherever we see 1, it implies 2, and I'm sure you can guess what a 2 implies :)

00              aa
01              ab
02              ac
10   0 => a     ba
11   1 => b     bb
12   2 => c     bc
20              ca
21              cb
22              cc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...