阵列的不同组合(C#)

编程入门 行业动态 更新时间:2024-10-11 19:22:24
本文介绍了阵列的不同组合(C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我们如何找出一个数组的使用C#code中的元素的不同组合。 是否有任何内置的库函数这一点。?

有关,例如:假设一个数组的元素{2,3,4,5,6,7} 那么可能的组合会是2,3,4,5,6,7,2 3,2 4,2 3 3 4 5等

所以基本上笏我需要的是一个函数,它提供了不同组合的基础上它的输入,例如:梳(阵列,2)使输出2 3,1 2,3 4梳(排列3)给出输出1 2 3 2 3 4 4,3 5等

例如:对阵列有效comnbination = {1,2,3}和长度= 2的1个2,1 3,2 3 .....

解决方案

静态无效的主要() {     变种CNK =梳(新[] {1,2,3},2);     的foreach(在CNK变种C)     {     } } 公共静态的IEnumerable< INT [] GT;梳(INT []一,INT K) {     若(a == NULL ||则为a.length == 0 || K< 1 || K>则为a.length)         产生中断;     INT N =则为a.length;     // 1     如果(K == 1)         的for(int i = 0;我n种;我++)         {             产量返回新INT [] {A [1]};         }     其他         {             //ķ             的for(int i = 0;我n种 - K + 1;我++)             {                 VAR解析度=新INT [K]                     对于(INT T = I,C = 0,T<我+ K - 1;吨++,C ++)                         水库[C] = A [T];                 对于(INT J = I + K - 1; J&n种; J ++)                 {                     水库[K-1] = A [J]。                     得到的回报水库;                 }             }         } }

您应该采取的算法从这里,我的回答没有解决您的问题 Algorithm返回k个元素的所有组合从n个

how can we find out different combination of the elements of an array using c# code. are there any inbuilt library function for this.?

for eg: suppose an array has elements {2,3,4,5,6,7} then the possible combination would be 2,3,4,5,6,7,2 3,2 3 4,2 3 4 5, etc

so basically wat i need is a function which gives different combination based on its input for eg: comb(array,2) gives output 2 3,1 2,3 4 and comb(array,3) gives output 1 2 3,2 3 4,3 4 5 and so on

Eg: valid comnbination for array= {1, 2, 3} and length = 2 are 1 2,1 3,2 3 .....

解决方案

static void Main() { var cnk = comb(new [] {1,2,3},2); foreach ( var c in cnk) { } } public static IEnumerable<int[]> comb(int[] a, int k) { if (a == null || a.Length == 0 || k < 1 || k > a.Length) yield break; int n = a.Length; // 1 if ( k == 1) for ( int i = 0; i < n; i++) { yield return new int[] {a[i]}; } else { // k for ( int i = 0; i < n - k + 1; i++) { var res = new int[k]; for (int t = i, c = 0; t < i + k - 1; t++, c++) res[c] = a[t]; for (int j = i + k - 1; j < n; j++) { res[k-1] = a[j]; yield return res; } } } }

You should take the algorithm from here, my answer doesn't solve your problem Algorithm to return all combinations of k elements from n

更多推荐

阵列的不同组合(C#)

本文发布于:2023-10-19 18:52:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1508447.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   阵列

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!