2014-06-11 19 views
1

我已经在c#中编写了一个简单的程序,用于生成一组五个数字的不同组合。 生成的组合将存储在int数组中。它将被五读五读。不同数字及其关系的组合

int[] number = new int[no_of_combination]; 

我想知道在这些组合中重复了多少个数字。 例如{1 2 3 4 5}和{3 4 5 6 7}有三个重复的数字,它们是{3 4 5}

我的方法是将每个组合与所有其他组合进行比较。 对于n个组合,将会有n(n-1)/ 2个比较。结果(重复的数字及其相应的值)将存储在对象数组中。 如果n很大,比如100000,那么操作次数将会非常大。这消耗了大量的内存来存储结果。

int[] init = new int[6]; // 6 for no repeat,1,2,3,4 and 5, init counting the number of combinations in each repeated number group 
    RepeatedSet[,] S = new RepeatedSet[6,number.Length*number.Length]; 
    for(int i=0;i<number.Length-1;i++) 
    { 
     for(int j=i+1;j<number.Length;j++) 
     { 
      int no_of_repeated_number = 0; 
      int a = i, b = j;     
      for (int k = 0; k < 5; k++) 
      { 
       // counting number of repeated numbers 
       for (int l = 0; l < 5; l++) 
       { 
         if (n[a, k] == n[b, l]) 
         { 
          no_of_repeated_number++; 
         } 
       } 
       int[] repeated_number_set = new int[no_of_repeated_number]; 
       int count = 0; 
       // putting the repeated numbers value into array 
       for (int k = 0; k < 5; k++) 
       { 
         for (int l = 0; l < 5; l++) 
         { 
          if (n[a, k] == n[b, l]) 
          { 
           repeated_number_set[count] = n[a,k]; 
           count++; 
          } 
         } 
       } 
       // create objects to store the infomation 
       S[no_of_repeated_number, init[no_of_repeated_number]] = new RepeatedSet(a,b,repeated_number_set,repeated_number_set.Length); 
       init[no_of_repeated_number]++; 
      } 
     } 
    { 

类RepeatedSet:

class RepeatedSet 
    { 
     int combinationA = 0; // sequence no. of combination A 
     int combinationB = 0; // sequence no. of combination B 
     int[] repeat = new int[0]; 

     public RepeatedSet(int a, int b, int[] r, int size) 
     { 
      combinationA = a; 
      combinationB = b; 
      repeat = new int[size]; 
      repeat = r; 
     } 

     public int getcombinationA() 
     { 
      return this.combinationA; 
     } 

     public int getcombinationB() 
     { 
      return this.combinationB; 
     } 

     public int[] getRepeatedSet() 
     { 
      return this.repeat; 
     } 

我的问题:有没有更好的方式来完成任务,而不比较密集的操作?

+0

你应该张贴所有代码。即什么是'RepeatedSet'和'number'等。 –

+0

RepeatedSet class added – user3704347

回答

1

解决您的问题的最佳方法是使用字典,键是五个组中的数字,值是数值在这些组中出现的次数(假设每个数字在一组中最多出现一次五)。

遍历词典的按键,你可以很容易地确定一个数字是否

  • 超过五个全台独一无二的:重复次数等于1
  • 在五都组发生了一些:重复次数等于
  • 一些多次发生,但不多于所有集合

后来套数

只有几个指针。

using System.Collections.Generic; 
Dictionary<int, int> dictionary = new Dictionary<int, int>(); 

要计算另一号码:

int count; 
if (dictionary.TryGetValue(number, out count)){ 
    dictionary[number] = count + 1; 
} else { 
    dictionary[number] = 1; 
} 

研究结果

foreach (KeyValuePair<int, int> pair in dictionary){ 
    int number = pair.Key; 
    int count = pair.Value; 
    ... 
} 
+0

如何创建一个包含数字组合的所有可能性的字典? – user3704347

+0

查看我添加的片段。从http://www.dotnetperls.com/dictionary了解更多信息 – laune