Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - Getting all the combinations in an array

Say I have the following array:

var arr = new[] { "A", "B", "C" };

How can I produce all the possible combinations that contain only two characters and no two the same (e.g. AB would be the same as BA). For example, using the above array it would produce:

AB
AC
BC

Please note that this example has been simplified. The array and the length of the string required will be greater.

I'd really appreciate if someone could help.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Lets extend it, so maybe we can see the pattern:

string[] arr = new string[] { "A", "B", "C", "D", "E" };

//arr[0] + arr[1] = AB
//arr[0] + arr[2] = AC
//arr[0] + arr[3] = AD
//arr[0] + arr[4] = AE

//arr[1] + arr[2] = BC
//arr[1] + arr[3] = BD
//arr[1] + arr[4] = BE

//arr[2] + arr[3] = CD
//arr[2] + arr[4] = CE

//arr[3] + arr[4] = DE

I see two loops here.

  • The first (outer) loop goes from 0 to 4 (arr.Length - 1)
  • The second (inner) loop goes from the outer loops counter + 1 to 4 (arr.Length)

Now it should be easy to translate that to code!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...